Omiron Omiron - 2 months ago 14
React JSX Question

Reactjs and adding classes

I have a react component that is a form with various fields, I want to be able to hide various fields by passing in props. Id have a prop called hideElements, which contained a list of ids which would match to the refs of the form elements.

If I use jquery to get each element by its ref and add a "hidden" class in componentDidMount will it cause problems with react? Is there a better way to do it?

Answer

Is there a reason to use jQuery? Could you just conditionally hide or not display elements in the render method?

// Assuming props.hideElements = {'title' : true, 'email' : true};
render: function() {
    var hideElements = this.props.hideElements;
    return (
        <div>
            <input className={hideElements['title'] ? 'hide' : null} name="title" type="text"/>
            OR
            {hideElements['email'] ? null : <input name="email" type="text" />}
        </div>
    )
}

If you'd like to keep the render method neater, you could have the logic elsewhere in a variable or function and then output the results (either your elements or nothing).

render: function() {
    return (
        {this.renderInputTitle()}
        {this.renderInputEmail()}
    )
}