REACT

React Button: Syntax, Usage, and Examples

A React button lets you add interactive features to your React applications. Whether you're triggering a function, submitting a form, or navigating to another page, buttons in React provide a flexible and declarative way to manage user interaction. By combining HTML semantics with React's component-based design, you can build accessible and reusable UI elements.

How to Use a React Button

A React button is typically created using the standard <button> HTML element. However, instead of attaching logic through inline attributes or traditional DOM event listeners, React encourages handling events through functions and state.

Basic Syntax

Here’s a simple example of creating a button in React:

function App() {
  const handleClick = () => {
    alert("Button clicked!");
  };

  return (
    <button onClick={handleClick}>Click Me</button>
  );
}

In this case, the onClick attribute is connected to a function. When the button is pressed, React calls that function.

You can also create a button component:

function CustomButton({ label, onClick }) {
  return <button onClick={onClick}>{label}</button>;
}

Using components like this keeps your UI modular and reusable.

When to Use a Button in React

Use a React button whenever you want the user to trigger an action in your app. It could be as simple as logging a message or as complex as navigating between routes or submitting a form. Because React uses declarative UI, the logic you define runs within the React lifecycle, making your components predictable and easier to debug.

You might use a React button when:

  • The user should trigger a function, like toggling a setting or loading data.
  • You want to navigate to another route using React Router.
  • You're submitting form data or handling validation.
  • You’re building dynamic UI where button state or style changes based on conditions.
  • Accessibility or semantic HTML is important to your project.

Buttons serve as gateways to behavior, so you'll find them everywhere from authentication flows to shopping carts.

Examples of React Buttons in Real Projects

Button That Changes State

React buttons often modify component state to show or hide content.

function ToggleMessage() {
  const [isVisible, setIsVisible] = React.useState(false);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? "Hide" : "Show"} Message
      </button>
      {isVisible && <p>Hello from React!</p>}
    </div>
  );
}

This pattern is extremely common—toggling UI with a button click using state hooks.

React Navigate with Button

If you’re using React Router, you can navigate between routes using a button.

import { useNavigate } from 'react-router-dom';

function NavigateButton() {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate("/dashboard")}>
      Go to Dashboard
    </button>
  );
}

Instead of <Link>, which is used for navigation through anchor tags, a button in React can use the navigate function to go to different pages programmatically.

Disable a Button Based on Conditions

Buttons don’t always need to be active. You can control their state with props or internal logic.

function SubmitForm() {
  const [email, setEmail] = React.useState("");

  return (
    <form>
      <inputtype="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button disabled={!email}>Submit</button>
    </form>
  );
}

React gives you full control over when a button is clickable.

Styling a Button in React

You can style a React button using inline styles, CSS modules, or frameworks like Tailwind or styled-components.

function StyledButton() {
  return (
    <button style={{ padding: '10px', backgroundColor: 'royalblue', color: 'white' }}>
      Save
    </button>
  );
}

Or you can pass class names:

function PrimaryButton({ label }) {
  return <button className="btn btn-primary">{label}</button>;
}

Reusable buttons with consistent style are essential in component libraries.

Learn More About Buttons in React

Forms and Submission with React JS Button

When you're building forms, React buttons often trigger form submissions. By default, a button inside a <form> has a type="submit" behavior.

function ContactForm() {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Form submitted");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Name" />
      <button type="submit">Send</button>
    </form>
  );
}

React handles form logic declaratively, which helps avoid bugs related to uncontrolled input.

Custom Button Components

Instead of duplicating button styles and logic, you can build a custom button component once and reuse it throughout your app.

function Button({ children, onClick, variant }) {
  const className = variant === "primary" ? "btn btn-primary" : "btn btn-secondary";
  return (
    <button className={className} onClick={onClick}>
      {children}
    </button>
  );
}

This pattern allows consistent UX and styling across your React project.

Keyboard Accessibility

React makes it easy to follow accessibility best practices. By using a <button> element rather than a clickable <div>, keyboard users can tab and press Enter or Spacebar to activate the button. This also gives screen readers the correct semantics automatically.

If you use custom elements, like <div> with onClick, remember to add:

  • tabIndex="0"
  • ARIA attributes like role="button"
  • onKeyDown logic for key events

But it’s always better to use native buttons when possible.

Conditional Rendering with Buttons

React makes it easy to show or hide buttons based on state or props.

function DeleteConfirmation({ isAdmin }) {
  if (!isAdmin) return null;

  return <button>Delete Account</button>;
}

Conditional rendering helps you tailor buttons to the user’s role or the app’s context.

Buttons and React Portals

If you're building modals or dropdowns, you might want to render buttons inside React Portals. This allows you to control z-index and focus management while keeping your DOM clean.

import ReactDOM from "react-dom";

function Modal({ onClose }) {
  return ReactDOM.createPortal(
    <button onClick={onClose}>Close Modal</button>,
    document.getElementById("modal-root")
  );
}

Buttons remain fully interactive inside portals because React handles all event delegation efficiently.

Handling Long or Async Actions

Some actions might take time to complete. You can disable the button or show a loading state to avoid duplicate clicks.

function LoadButton() {
  const [loading, setLoading] = React.useState(false);

  const handleClick = async () => {
    setLoading(true);
    await fetchData(); // Simulated API call
    setLoading(false);
  };

  return (
    <button onClick={handleClick} disabled={loading}>
      {loading ? "Loading..." : "Fetch Data"}
    </button>
  );
}

This improves UX and prevents accidental form submissions or duplicated network requests.

Best Practices for React Buttons

  • Always use semantic <button> elements for clickable actions.
  • Use descriptive labels like “Save”, “Submit”, or “Continue”.
  • Avoid using buttons for navigation unless you're handling routes correctly.
  • Provide visual feedback with styles, animations, or loading indicators.
  • Keep buttons accessible by default using native elements and ARIA attributes only when needed.
  • Reuse button components and avoid duplicating logic or design.
  • Combine buttons with form controls to manage state and data flow cleanly.

React button components are more than just clickable elements—they control how users interact with your application. Whether you’re handling navigation, triggering events, or submitting forms, building flexible and accessible buttons is a core part of modern React development.

With consistent design, clear state management, and good accessibility practices, your React buttons will feel responsive and intuitive across any project.

Learn to Code in React for Free
Start learning now
button icon
To advance beyond this tutorial and learn React by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH