I am new in react world. So this is may be a silly question I am trying to do something similar to this https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator but instead of display the strings I want to display properties value
Something like this:
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? {prop1} : {prop2}}</b> logged in.
</div>
);
}
If I do that I get an error. But I can see the value of {prop1} and {prop2} if I put them outside of the if clause.
What other ways I could do something like this? Have two returns would be ugly in my optinion because I would have some duplicated code when only what I want is to display some diffrerent string
EDIT: The error message is this
react-dom.development.js:14793 Uncaught Error: Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead.
3 Answers 3
Assuming that prop1 and prop2 are strings (or numbers) you could do:
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? prop1 : prop2}</b> logged in.
</div>
);
}
if they are them-self functions returning React elements :
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? prop1() : prop2()}</b> logged in.
</div>
);
}
What you did is to render a javascript object do the dom as is
Comments
depends on what type prop1 & prop2 are but try:
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? prop1 : prop2}</b> logged in.
</div>
);
}
Comments
When you use {} in your jsx code, you say react that it's a javascript code, and when you use {} inside {} you try to make an object. And as @Jerome replied you just need to remove the curly brackets. {isLoggedIn ? prop1 : prop2}. Also you can use jsx code inside {}, for example: {isLoading ? <Loading/> : <MainBlock/>}.
this.props.prop1andthis.props.prop2?