Babakness
Babakness

Reputation: 3134

React Component and useState

I'm using React with create-react-app w/ React Hooks (^16.7.0-alpha)

I'm calling useState as such const [Foo, setFoo] = useState( ({bar}) => <div> Hello {bar}</div> )

I return JSX as such <div><Foo bar='x'/></div>

I've also tried like this <div>{ Foo({bar: 'x'}) }</div>

Yet React complains that Foo is an element and not a component.

How can I make this work?

Upvotes: 2

Views: 343

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282030

When you pass a function to useState react evaluates that function and sets the returned value as the initial state. and hence in your case, firstly the destructured variable bar will be undefined and secondly Foo will be returned as <div> Hello {bar}</div> and not the React component.

Also you shouldn't be setting component in the React state. Instead simply define them as a functional component

const Foo = ({bar}) => <div> Hello {bar}</div> );

If at all in an extreme case you want to store a component in state it would work like

  const [Foo, setFoo] = useState(() => ({ bar }) => (
    <div> Hello {bar}</div>
  ));

Working demo

Upvotes: 2

Related Questions