0
0
Reactframework~5 mins

Reusable UI components in React

Choose your learning style9 modes available
Introduction

Reusable UI components help you build parts of your app once and use them many times. This saves time and keeps your app consistent.

When you want to show the same button style in many places.
When you need a form input that behaves the same everywhere.
When you want to create a card layout that repeats with different content.
When you want to keep your code clean and easy to update.
When you want to share UI parts between different pages or projects.
Syntax
React
function ComponentName(props) {
  return (
    <div>{props.children}</div>
  );
}

// Usage
<ComponentName>Content here</ComponentName>
Use a function that returns JSX to create a component.
Pass data using props to customize the component.
Examples
A simple button component that shows text from the label prop.
React
function Button(props) {
  return <button>{props.label}</button>;
}

<Button label="Click me" />
A card component that shows a title and any nested content inside.
React
function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div>{children}</div>
    </div>
  );
}

<Card title="Hello">This is inside the card.</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.

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

Summary

Reusable components save time and keep your app consistent.

Use props to customize components for different uses.

Make components accessible and easy to use everywhere.