Reputation: 360
I'm just starting to learn react and I don't understand why this is happening. My code is just to create a random number and display it in the DOM, then say that the number is a big number or a small number.
I have react-dom, react and Babel added to my script. Here's my codepen.
Here's my HTML Code.
<div id="root"></div>
<div id="rand"></div>
Here's my JavaScript code. The rand component is not being rendered when I have the <p>{bigOrSmall} Number !</p>
. When I remove this line, It works and the random number Your Random Number : [anything]
is shown.
const Head = () => {
return <h1>Random Number</h1>
}
const RandomNum = () => {
const rand = Math.floor(Math.random() * 10);
if (rand >= 5) {
const bigOrSmall = "Big"
}
else {
const bigOrSmall = "Small"
}
return (
<>
<p>Your Number is: {rand}</p>
<p>{bigOrSmall} Number !</p>
</>
);
}
ReactDOM.render(<Head/>, document.getElementById("root"))
ReactDOM.render(<RandomNum/>, document.getElementById("rand"))
Upvotes: 0
Views: 43
Reputation: 20701
const is block scoped. So your variable is not accessible outside the curly braces.
Use let bigOrSmall;
above the curly braces and inside manipulate their values.
When you move your variable outside, now its scope is the curly braces of the function component starting after Random = () => {
and ending in the last line }
.
Upvotes: 1
Reputation: 16606
The problem is you have a scoping error in your RandomNum
component. You need to define bigOrSmall
outside of your if
statement. The following will work:
const RandomNum = () => {
let bigOrSmall;
const rand = Math.floor(Math.random() * 10);
if (rand >= 5) {
bigOrSmall = "Big"
}
else {
bigOrSmall = "Small"
}
return (
<>
<p>Your Number is: {rand}</p>
<p>{bigOrSmall} Number !</p>
</>
);
}
Upvotes: 1