How to comment code block in JSX (React)

Asked

Viewed 12,658 times

10

I want to know if it is possible to comment on a code block inside the render() method in React, I tried every way I know and none of them worked.

render() {
    return (
      <div className="Events">
        <div className="EventDescription">Multi-Eventos</div>
        <div className="EventHeader">
          <Button onClick={this.addEvent.bind(this)} bsStyle="warning">Adicionar Eventos 
            <FontAwesome name="chevron-down"/>
          </Button>
          // Não funciona
          <!-- Não funciona -->
          /* Não funciona */
          -- Não funciona
        </div>
      </div>
    );
  }

2 answers

13


To comment on jsx, you should put braces around the comments, otherwise it’s like you did in your second example (/* Não funciona */):

{/* COMENTÁRIO JSX */}

8

You can read about this on react documentation, but basically there are 4 different types.

I made an example jsFiddle here: https://jsfiddle.net/mk50r5qt/

The code is:

var Span = React.createClass({
    render: function() {
        return (
            <span style={{color: this.props.color}}>
                {this.props.text}
            </span>
        );
    }
});


var Hello = React.createClass({
    render: function() {
        return (<div>
            <Span {...this.props} text={'Hello'} />
            {/* comentário entre componentes */}
            <Span {...this.props} text={' World!'} />
        </div>);
    }
});

ReactDOM.render(
    // comentário ao estilo JavaScript
    < Hello /* comentário dentro do componente */ name="World" /*
    comentários de multiplas linhas funcionam também!
    */ color={'blue'}
    /> ,
    document.getElementById('container')
);

#1 - comments between components:

within JSX, between components the syntax is {/* texto aqui */}. The reason for the braces {} is to interpret as Javascript and then we know how to comment.

#2 - comments off and before components:

render: function() {
    return ( 
        // comentário antes do componente contentor...
        <div>

#3 - comments within component tags on the same line:

<Hello /* comentário dentro do componente */ name="World" />

#4 - comments within component tags on multiple lines:

<Hello name="World"
   /*
      comentários de multiplas linhas funcionam também!
   */ 
   color={'blue'}
/>

http://chenglou.github.io/react/docs/jsx-in-depth.html#comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.