passings array as props in reactjs
The curly braces only need to be used within JSX elements. Like this:
<MyComponent somProp={['something']} />
In the case above, the {}
is the way of saying: "Evaluate the expression that I passed within and pass it as a prop". Within the {}
you can pass any valid JavaScript object or expression. Note that if you pass a string, and specifically for strings, you don't need the curly braces... like <MyComponent somProp="something" />
.
The above code is the equivalent of this:
var myArray = ['something'];
<MyComponent somProp={myArray} />
You actually don't need to specify PropTypes
at all to use props. It's just a good way to document and verify prop types during development.
You are using the {}
correctly. {}
will return the value of the expression inside.
However, {['everyone']}
doesn't make much sense. Here you are asking React to return the value of the array itself, rather than one of the elements/values within the array.
To get the first value out of your array, you should be doing: {this.props.config[0]}
since the value "everyone" is at the 0 index of the array.
If your array had multiple values, you would do something along the lines of:
render: function() {
var values = this.props.config.map(function(value, i){
return (
<p>value</p>
);
});
return (
<div className="navigation">
helloworld {values};
</div>
);
}
If you truly to mean to actually print out the array itself, and not a particular value within it, you have two good options:
render: function() {
return (
<div className="navigation">
helloworld {this.props.config.toString()};
</div>
);
}
Or
render: function() {
return (
<div className="navigation">
helloworld {JSON.stringify(this.props.config)};
</div>
);
}