Hello, I have a question about using props with conditional statements (if...then). Would it be possible to write a function instead?
For example, if I wanted to create a button to read a specific statement depending on whether the user is on a free Codecademy account versus a paid Pro account:
This is the way we learn to use props in the exercise:
export class Welcome extends React.Component {
render() {
if (this.props.paidAccount == false) {
return (
<button>
Upgrade to Pro Today!
</button>
);
} else {
return (
<button>
Thanks for Being a Pro!
</button>
);
}
}
}
And this is the way I was interested in writing it using a function:
export class Welcome extends React.Component {
const clickMe = () => {
if (this.props.paidAccount === true) {
return ‘Thanks for Being a Pro!’;
} else {
return ‘Upgrade to Pro Today!’;
}
};
render() {
return (
<button>
{clickMe}
</button>
);
}
}
}
class App extends React.Component {
render() {
return (
<div>
<h1>
Hullo and, "Welcome to The Newzz," "On Line!"
</h1>
<Greeting name="Alison" />
<article>
Latest: where is my phone?
</article>
</div>
);
}
}
The property this.props.signedIn is not yet defined. This would normally mean that the evaluation of it should be ‘false’ since it’s non-existent in the code below (the 2nd <div> is my attempt to see what gets passed in props):
However, according to what’s being rendered to the screen, not defining the property seems to have evaluated to ‘true’ as we’re seeing content from the ‘Hi there’ branch. To confirm, the 2nd <div> I added which outputs the text for this.props shows: {"name":"Alison"}
Is this the expected behavior, or am I missing something?
Because false is being used as a Boolean.
[have a look at the condition if (this.props.signedIn === false) in Greeting.js ]
If you wrote the property as signedIn = "false", then you would be using a string instead of a Boolean. You would have to modify the condition in Greeting.js to if (this.props.signedIn === "false")
In this context, using false as a Boolean is more sensible. Hence signedIn={false} is a better choice.