John Winston
John Winston

Reputation: 1481

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

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.

Upvotes: 3

Views: 784

Answers (2)

Rhyan-WoodsAndWalker
Rhyan-WoodsAndWalker

Reputation: 629

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

Upvotes: 1

Rashomon
Rashomon

Reputation: 6792

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

Upvotes: 2

Related Questions