0
0
Reactframework~5 mins

Reusable components in React

Choose your learning style9 modes available
Introduction

Reusable components let you build parts of your app once and use them many times. This saves time and keeps your code neat.

When you have a button style used in many places.
When you want to show a user profile card in different screens.
When you need a form input that behaves the same everywhere.
When you want to keep your app organized by breaking UI into small pieces.
When you want to easily update a feature in one place and see changes everywhere.
Syntax
React
function ComponentName(props) {
  return (
    <div>{props.content}</div>
  );
}

// Usage
<ComponentName content="Hello!" />
Components are functions that return UI elements.
Props are inputs you give to components to customize them.
Examples
A simple button component that shows text from props.
React
function Button(props) {
  return <button>{props.label}</button>;
}

<Button label="Click me" />
Using destructuring to get props directly for cleaner code.
React
function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

<Greeting name="Alice" />
Component with children lets you put any content inside it.
React
function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div>{children}</div>
    </div>
  );
}

<Card title="My Card">
  <p>This is inside the card.</p>
</Card>
Sample Program

This app shows two buttons using the same reusable Button component. Each button has its own label and click action. The buttons are accessible with aria-label and keyboard friendly.

React
import React from 'react';

function Button({ label, onClick }) {
  return (
    <button onClick={onClick} aria-label={label}>
      {label}
    </button>
  );
}

export default function App() {
  const handleClick = () => alert('Button clicked!');

  return (
    <main>
      <h1>Reusable Button Example</h1>
      <Button label="Say Hello" onClick={handleClick} />
      <Button label="Say Goodbye" onClick={() => alert('Goodbye!')} />
    </main>
  );
}
OutputSuccess
Important Notes

Always give components clear names that describe what they do.

Use props to make components flexible and reusable in different places.

Remember to add accessibility features like aria-label for better user experience.

Summary

Reusable components help you write less code and keep your app organized.

They take inputs called props to change how they look or behave.

You can use the same component many times with different props.