1

I am learning ReactJS and I wanted to know the difference in using curly braces and parenthesis for return statements.
Here is a block of code

class App extends React.Component {
    constructor() {
        super();
        this.state = {
            count: 0
        };
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        this.setState(prevState => {
            return {
                count: prevState.count + 1
            }
        })
    }
    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <br />
                <button onClick={this.handleClick}>Change!</button>
            </div>
        );
    }
}

export default App

In the handleClick function, return has curly braces and in the render function, it has parenthesis.
Interchanging them in either case gives me an Error.
So...I just wanted to know if there is any difference and which one is to be used when

Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
  • 1
    a curly bracket would generally denote an object that is being returned, the parenthesis here aren't needed as it is being used as a grouping operator to group the jsx being returned. remember this gets transpiled from jsx to `return React.createElement('div', ...)` – John Ruddell Apr 16 '20 at 17:50
  • The meaning of `()` is listed under "Grouping Operator' on the first duplicate. – Quentin Apr 16 '20 at 17:51
  • 1
    @JohnRuddell - It's common practice in React-world because otherwise people have a tendency to put a newline after `return` and start the JSX on the next line...which ends up returning `undefined`, since ASI inserts a `;` after the `return`. :-( Personally, I prefer `return
    ` but that seems not to be popular for some reason.
    – T.J. Crowder Apr 16 '20 at 17:52
  • 1
    @T.J.Crowder yep, i prefer that as well. good information for the question though :) – John Ruddell Apr 16 '20 at 17:55
  • @JohnRuddell - Glad I'm not the only one! – T.J. Crowder Apr 16 '20 at 18:09

0 Answers0