When to actually use curly braces in React

Jasterix - Jun 27 '19 - - Dev Community

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 { this.props.name }
  • setState this.setState({ number : "james" })
  • are doing string interpolation I love ${snack.name}

Brief example of curly braces in action:

codepen

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>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player