Search code examples
reactjshrefreusability

Reutilizing components on React


I'm working with React and i'm trying to reuse some code because i have to put a button on every page; so i declared it as a function on another component and i'm trying to call it on one of my pages, but i'm getting an error:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

I have the component:

    export const whatsappLink = () => {
      return (
        <a
          href=""
          className="link-simulator floating"
          target="_blank"
        >
          <i className="fab fa-whatsapp my-float"></i>
        </a>
      );

};

And i'm call in it like this on my render:

<div>{whatsappLink}</div>

Why am i getting this error? And how should i call it?


Solution

  • You should use JSX tag syntax to render the functional component, also the name should be PascalCased i.e first letter should be uppercased. Trying to render a component like {whatsappLink} will cause an error because functions can not be valid React children.

    // when trying to render the WhatsappLink component
    <div>
      <WhatsappLink/>
    </div>
    
    // define WhatsappLink component
    export const WhatsappLink = () => {
       return (
         <a
           href=""
           className="link-simulator floating"
           target="_blank"
         >
           <i className="fab fa-whatsapp my-float"></i>
         </a>
       );
    };