1

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?

1
  • If adding a class doesn't actually change the presence of some elements in the DOM it shouldn't be an issue even if you should avoid it. If the CSS class you give to the component change the presence of a component in the DOM it can cause issue with React not knowing about the fact an element is not there anymore. What you want to do is totally feasible the react way, without having to use jQuery. Commented Sep 21, 2015 at 0:44

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey! That's what I use!
0

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

1 Comment

There was no particular reason for jQuery apart from that being my background, and still learning how to achieve similar things with react. This looks good I'll give it a go
0

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>


        )
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.