Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React not rendering classes on elements

I currently have two files, an app.js and an index.html and when I try to render a form with some CSS classes, the HTML elements display but the classes are missing.

This is my app.js:

var Form = React.createClass({
    handleClick: function() {
        alert('click')
    },
    render: function() {
        return (
            <div>
                <input class='form-control' type='text' name='list-name'/>
                <button class="btn btn-primary" onClick={this.handleClick}>Submit</button>
            </div>
        );
    }
});

ReactDOM.render(<Form/>,document.getElementById('app'));

This is my HTML body:

<div class="container">
    <h1>Title</h1>
    <div id="app" class="center"></div>
</div>
like image 394
user1775500 Avatar asked Sep 12 '16 01:09

user1775500


1 Answers

Because class can conflict with ECMAScript (it's a reserved keyword), React developers chose to use className as the attribute for HTML elements for classes instead of class. Per the React documentation:

Note: Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like className and htmlFor, respectively. Source

Since for and class are reserved keywords of ECMAScript (of which JavaScript is an implementation), they cannot be used as XML attribute names. That means attributes of tags such as div or input. Thus, use className to signify an HTML element's class. Here's an applicable example:

return (
    <div>
        <input className='form-control' type='text' name='list-name'/>
        <button className="btn btn-primary" onClick={this.handleClick}>Submit</button>
    </div>
);

Notice that className is used in place of class.

like image 163
Andrew Li Avatar answered Oct 27 '22 01:10

Andrew Li