I'm rendering different texts depending on a given variable, and I simply want to render
at a particular variable within h2 tag.
I tried using regex \r and \n (and the bination) to render, but it hasn't work.
render() {
let {tracker} = this.props, headline;
switch(tracker){
case 1:
headline = 'That is amazing!'
break;
case 2:
headline = 'Too bad.<br />Try again'
break;
}
return(
<h2>{headline}</h2>
)
}
I'm rendering different texts depending on a given variable, and I simply want to render
at a particular variable within h2 tag.
I tried using regex \r and \n (and the bination) to render, but it hasn't work.
render() {
let {tracker} = this.props, headline;
switch(tracker){
case 1:
headline = 'That is amazing!'
break;
case 2:
headline = 'Too bad.<br />Try again'
break;
}
return(
<h2>{headline}</h2>
)
}
let {tracker, headline} = this.props;
?
– Chris
Commented
Aug 6, 2019 at 20:39
It seems like you want to render a different headline depending on the tracker value passed from the parent.
Let's see what's wrong with the code below.
render() {
let {tracker} = this.props, headline;
switch(tracker){
case 1:
headline = 'That is amazing!'
break;
case 2:
headline = 'Too bad.<br />Try again'
break;
}
return(
<h2>{headline}</h2>
)
}
First of all, the declaration of this.props, headline
seems very unintuitive.
Let's separate it into two.
let headline;
let { tracker } = this.props;
Now, switch
checks for the condition and try to assign the headline value.
switch(tracker){
case 1:
headline = 'That is amazing!'
break;
case 2:
headline = 'Too bad.<br />Try again'
break;
}
Now that's problematic because when you return <h2>{headline}</h2>
, what React is expecting is an element.
The valid expression can be of string, number, or another JSX element.
The case 1, is OK, because it's a string.
But the reason you are having trouble with case 2 is because <br />
is part of a string, thus React considers it a string (and try to decode it).
So what can we do?
You can convert the case 2 into an element by getting rid of quotes, and wrapping it into an element. You can use any elements such as div
, React.Fragmenet
(<>/).
switch(tracker){
case 1:
headline = 'That is amazing!'
break;
case 2:
headline = <>Too bad.<br />Try again</>
// or use "div" or other element.
// headline = <div>Too bad.<br />Try again</div>
break;
}
Another way is to render it dangerously. You should never do this unless you know what you are doing. I won't go further as this is probably not what you want.
The code you used using switch is what's called an "imperative" code. (You specify "how" the ponent should work).
But React is declarative in nature, and you tell "what" the ponent should do.
So let's fix it up a bit and make it React-like.
render() {
//