Omiron
Omiron

Reputation: 407

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?

Upvotes: 1

Views: 3249

Answers (3)

Mr. Durga prasad patra
Mr. Durga prasad patra

Reputation: 361

You can use the refs to add a new class in React.

import React from "react";
export default class Text extends React.Component {
    constructor() {
        super()
    }
    click(){
        this.refs.myDiv.className="box formControl inputBox";//using button to add a class
    }
    componentDidMount(){
        this.refs.myDiv.className="box formControl inputBox";// add a class
    }
    render() {
        return (
            <div>
                <div ref="myDiv"></div>
                <button onClick={this.click.bind(this)}>click</button>
            </div>


        )
    }

}

Upvotes: 0

Cristian Sava
Cristian Sava

Reputation: 106

You can use the classnames library and hide the fields with css. This way you keep your react code clean and don't have tons of if statements.

Upvotes: 1

Rick Jolly
Rick Jolly

Reputation: 3009

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()}
    )
}

Upvotes: 0

Related Questions