Home > Blockchain >  How to define a component as default value for a prop in React?
How to define a component as default value for a prop in React?

Time:02-07

How can I do something like this correctly in React?


import Bar from './Bar.jsx'

const Foo = ({ icon = <Bar />}) => {
  // ...
}

export default Foo

Right now using icon = <Bar /> will simple give parsing error.

CodePudding user response:

Use capitalized Icon prop to be able to use it as a component:

const Bar = ({}) => {
  return <div>Bar</div>;
};

const Foo = ({ Icon = Bar }) => {
  return (
    <div>
      <Icon />
    </div>
  );
};

Live

CodePudding user response:

Don't include the <>'s, just assign it however it's imported (so Bar in this case).

You'll need to make the icon prop have a capital I, then you can use <Icon /> to call any component passed to it.

If Bar has any props, add them to Icon and they'll be passed through to Bar.

import Bar from './Bar.jsx'

const Foo = ({ Icon = Bar }) => {
  return (
    <Icon />
  )
}

export default Foo
  •  Tags:  
  • Related