How to reuse a React component by displaying it differently?

Asked

Viewed 41 times

1

I have a component called Header and wish to reuse it in a few more pages. When I do the import Header from './Header' and call him on the page desired, it’s all right.

What I wish is to bring the component without the Button to the new page. How can I do this?

Parent component:

const PageDefault = () => {
  return <Header />;
};
    
export default PageDefault;

Component Header:

const Header = () => {
  return (
    <nav className="Header">
      <Link to="/">
        <img className="Sena" src={Sena} alt="sena imagem" />
      </Link>

      <Button as={Link} className="Button" to="/sena/bel">
        Registrar
      </Button>
    </nav>
  );
};

export default Header;

1 answer

1


If it makes sense that this button is part of Header and appear on just a few occasions, you can do:

const Header = ({ withButton }) => {
  return (
    <nav>
      <Link />

      {withButton && <Button />}
    </nav>
  );
}

And when you want him to have the button, use:

return <Header withButton={true} />; // Ou <Header withButton />

If this button is extra content from a specific screen, you can receive a component as prop:

const Header = ({ extraContent }) => {
  return (
    <nav>
      <Link />

      {extraContent}
    </nav>
  );
}

And call the component that way:

const button = <Button />;

return <Header extraContent={button} />
  • Oops!!! Thank you!! That’s just what I needed! Be able to solve here. Thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.