skip to Main Content

I can pass a styled-component(Text component) like

export const Text = styled.span`
  font-size: 16px;
  color: red;
`;

Text.displayName = 'Text';


const Parent = () => {
  return (
    <>
      <Child Text={Text} />
    </>
  );
};

but now like this

  <Child Text={<Text />} />

I get an error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Is there a way to pass Text component like this <Child Text={<Text />} />?

2

Answers


  1. Yes, but you have to render it like this:

    function Child({ Text }) {
      return (
        <>{Text}</>
      )
    }
    
    Login or Signup to reply.
  2. No, in your example "Text" is not a react component but a mere object. A react component is declared as a function. For example:

    const regularObject = {"text": "I am just an object"};
    
    const MyComponent= (props) => {
      return <p>I am a component that uses props</p>;
      // Do something with the props...
    };
    
    const SubComponent= () => {
      return <p>I am a Subcomponent</p>;
    };
    
    const App = () => {
      return <MyComponent props={<SubComponent />} />; // OR props={regularObject}
      
    };
    
    // The following will NOT work, as it is not a component:
    const App = () => {
      return <MyComponent props={<regularObject />} />;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search