Pasing objects as a component property in React JSX

A Beginner Reaction:

React.renderComponent(
  <MyComponent item={name: "A Name", description: "---"} />,
  document.getElementById('container')
);

Console Error:

JSX value should be either an expression or a quoted JSX text

It doesn't seem to work like that. I searched for React documentation for a while, but haven't bought it yet.

+4
source share
2 answers

You are not passing the value correctly item. foo={...}denotes an expression in JSX, that is, the value of prop must be evaluated as JavaScript. Then you are missing an {...}object literal. It should be

<MyComponent item={{name: "A Name", description: "---"}} />
//                 ^---       object literal       ---^
//                ^-----        expression        -----^

Alternatively, if you do not find this syntax very readable, you can first assign the object to a variable:

var item = {name: "A Name", description: "---"};
// ...
<MyComponent item={item} />

See https://facebook.imtqy.com/react/docs/jsx-in-depth.html#attribute-expressions

+20
source

, , MyComponent this.props.name this.props.description this.props.item.name this.props.item.description, :

var item = {name: "A Name", description: "---"};
<MyComponent {...item} />
0

Source: https://habr.com/ru/post/1541850/


All Articles