MERN

⌘K
  1. Home
  2. Docs
  3. MERN
  4. reusable components

reusable components

Creating reusable components is a core principle in React and Next.js. Here’s a step-by-step guide on how to create and use a reusable button component as an example:

Step 1: Define the Component

Create a new file for your reusable component. For a button, you might call it Button.js and place it in a components directory.

// components/Button.js

const Button = ({ children, onClick, className }) => {
  return (
    <button onClick={onClick} className={`btn ${className}`}>
      {children}
    </button>
  );
};

export default Button;
JavaScript

Step 2: Add Styles

Create a CSS module for your component called Button.module.css in the same directory:

/* components/Button.module.css */

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #007bff;
  color: white;
  font-size: 16px;
}

.btn:hover {
  background-color: #0056b3;
}
JavaScript

Then, import this CSS module in your component:





// components/Button.js

import styles from './Button.module.css';

const Button = ({ children, onClick }) => {
  return (
    <button onClick={onClick} className={styles.btn}>
      {children}
    </button>
  );
};

export default Button;
JavaScript

Step 3: Use the Component in a Page

Now, you can import and use this Button component in any of your pages or other components.

// pages/index.js

import Button from '../components/Button';

const HomePage = () => {
  const handleClick = () => {
    console.log('Button clicked!');
  };

  return (
    <div>
      <h1>Welcome to My Page</h1>
      <Button onClick={handleClick}>Click Me!</Button>
    </div>
  );
};

export default HomePage;
JavaScript

Step 4: Reuse the Component

You can reuse the Button component as many times as you want throughout your application, passing different content (children) and functions (onClick) as props.

// Another example in pages/about.js

import Button from '../components/Button';

const AboutPage = () => {
  return (
    <div>
      <h1>About Us</h1>
      <Button onClick={() => console.log('Contact us!')}>Contact Us</Button>
      <Button onClick={() => console.log('Learn more!')}>Learn More</Button>
    </div>
  );
};

export default AboutPage;
JavaScript

How can we help?