To answer that question, it would be easier to explain when you don't need a curly brace
3 instances where you don't need a curly brace:
- around a string
<Component propKey = " " />
- around the prop key
<Component propKey = {this.prop.thing} />
- creating an id or className
<div id="hello">
Otherwise, you will need to use a curly brace. The good news, aside from example #2, it's always better to err on the side of using the brace.
But here are some common examples of when you need to use curly braces.
Use curly braces where you:
- render your JSX element
render() { return goes here }
- initialize state
state = { name: "jeff" }
- reference props
{ this.props.name }
- setState
this.setState({ number : "james" })
- are doing string interpolation
I love ${snack.name}
Brief example of curly braces in action:
class Toggle extends React.Component {
state = {
toggleOn: true
};
handleClick= () => {
this.setState({
toggleOn: !this.state.toggleOn
});
}
render() {
const buttonStyle = {};
if (this.state.toggleOn) {
buttonStyle.backgroundColor = "red"
} else {
buttonStyle.backgroundColor = "blue"
}
return (
<button style={buttonStyle} onClick={this.handleClick}>
{this.state.toggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
In keeping with tradition, here is a great resource to learn more about JSX and its curly braces
Top comments (2)
Sweet and short. Thank you for this. I make mistakes with curly braces from time to time so reminders on how to use them is always welcome.
On the topic of string, I tend to forget that Javascript has an enhanced version of string called template strings and curly braces are required in order to use them.
Good point. I'll add that to the list since string literals are pretty commonly used