Reputation: 1403
I am using React.js in some project and I wanted to send a prop only if a condition is true, what I don't want is to send null values or empty stuff as the following example (or this question):
return (
<SomeComponent
prop1={foo === true ? "value" : null}
/>
);
I want to send the whole prop (not only its value) if a condition is true, something like this:
render: function(){
...
return (
<SomeComponent
{if(foo === true) prop1="value"}
/>
);
}
I also tried
...
var prop1;
if(foo === true) prop1 = "prop1='value'";
return <SomeComponent {prop1} />;
and of course something like
...
return (
</SomeComponent
{foo === true ? prop1="value" : ""}
/>
);
In all cases I got a Unexpected token
error, I have been searching but I haven't found anything, is there any way to do that in react?
Thanks.
Upvotes: 3
Views: 7161
Reputation: 656
Well even if you send the undefined values, you will always have the chance to validate in either of the two functions: componentWillMount for the first load or componentWillReceiveProps after first load. Besides you can always have the render function to validate. But if I answer as per the approach you are trying.
render : function(){
if(foo === true)
return <SomeComponent prop1 ="value1" />;
else
return <SomeComponent />;
}
And in the rendered component you can use the getDefaultProps function to set the default values if you doesn't pass any prop values which is your second case.
Upvotes: 1
Reputation: 17064
Though not sure what's the purpose - with ES6 spread operator, you can do it like this:
const props = {};
if (foo === true) { // or just if (foo) {
props.prop1 = 'value';
}
<SomeComponent
{ ...props } />
Upvotes: 6