Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pasing objects as component property in React JSX

Tags:

reactjs

A React newbie's experiment:

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

Doesn't seem to work like that. I have digged React documentation for a while but no dice yet.

like image 726
Shawn Avatar asked Nov 30 '22 01:11

Shawn


1 Answers

You are not passing the value of item correctly. foo={...} denotes an expression in JSX, i.e. the prop value should be evaluated as JavaScript. You are then missing the {...} for the object literal. It should be

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

Alternatively, if you don't find that syntax very readable, you can assign the object to a variable first:

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

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

like image 83
Felix Kling Avatar answered Dec 05 '22 03:12

Felix Kling