Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: Passing nested props into React.createElement

I have code of the form

props = { user: {userattr1: 1, userattr2: 2}};
var element = React.createElement(MyReactClass, props);

i.e., where props is a nested object. When I try to compile the above code I get the error:

Warning: Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child.

I've been looking online and it seems that nested objects are perfectly permissible as props. How can I resolve my error?

Edit: MyReactClass looks something like this:

var MyReactClass = React.createClass({
  render: function () {
    <div>{this.props.user}</div>
  }
})
like image 918
Allen Avatar asked May 25 '15 14:05

Allen


Video Answer


2 Answers

I don't think the problem, you are having is related to a nested object as props. Here it is an example:

var Hello = React.createClass({
    render: function() {
        return <div>Hello {this.props.user.name}</div>;
    }
});

var props = { user: {name: "World"}};
React.render(React.createElement(Hello, props), document.getElementById('container'));

https://jsfiddle.net/urjmndzk

More likely, your problem is related to how you are setting the keys of the children components. However, it is hard to tell without seeing the entire code.

This is a link to the creeateFragment function, it may help you. https://facebook.github.io/react/docs/create-fragment.html

like image 88
Giuseppe Pes Avatar answered Oct 07 '22 18:10

Giuseppe Pes


If you're using JSX, you can also pass a nested object as a prop by building the object like this:

<HelloWorldClass user={{name:'Kyle'}} />

Syntax Example in Stack Snipets

// function component syntax
function HelloWorldFunc(props) {
  return (
    <div>Hello, {props.user.name} </div>
  );
}
// class component syntax
class HelloWorldClass extends React.Component {
  render() {
    return (
      <div >
        Hello, {this.props.user.name}
      </div>
    );
  }
}

// createElement syntax
const helloCreate = React.createElement(HelloWorldFunc, {user:{name:'Kyle'}});
// JSX syntax
const helloJSX = <HelloWorldClass user={{name:'Kyle'}} />

ReactDOM.render(
  <div>
    {helloCreate}
    {helloJSX}
  </div>
,document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 41
KyleMit Avatar answered Oct 07 '22 19:10

KyleMit