DEV Community


Posted on


When to actually use curly braces in React

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:

  1. around a string <Component propKey = " " />
  2. around the prop key <Component propKey = {this.prop.thing} />
  3. 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 { }
  • setState this.setState({ number : "james" })
  • are doing string interpolation I love ${}

Brief example of curly braces in action:


class Toggle extends React.Component {
state = {
  toggleOn: true

  handleClick= () => {
      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'}
Enter fullscreen mode Exit fullscreen mode

In keeping with tradition, here is a great resource to learn more about JSX and its curly braces

Top comments (2)

wanzulfikri profile image

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.

jasterix profile image

Good point. I'll add that to the list since string literals are pretty commonly used