user1725382 user1725382 - 2 months ago 67
React JSX Question

show or hide element in react.js

I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event. I am not loading any other library to the page, so I am looking for some native way using the React library. This is what I have so far. I would like to show the results div when the click event fires.



var Search= React.createClass({
handleClick: function (e) {
console.log(this.prop);
},
render: function() {
return <div className="date-range">
<input type="submit" value="Search" onClick={this.handleClick} />
</div>;
}
});

var Results = React.createClass({
render: function() {
return <div id="results" className="search-results">
Some Results
</div>;
}
});
React.renderComponent( <Search /> , document.body);

Answer

The key is to update the state of the component in the click handler using setState. When the state changes get applied, the render method gets called again with the new state:

var Search = React.createClass({
    getInitialState: function() {
        return { showResults: false };
    },
    onClick: function() {
        this.setState({ showResults: true });
    },
    render: function() {
        return (
            <div>
                <input type="submit" value="Search" onClick={this.onClick} />
                { this.state.showResults ? <Results /> : null }
            </div>
        );
    }
});

var Results = React.createClass({
    render: function() {
        return (
            <div id="results" className="search-results">
                Some Results
            </div>
        );
    }
});

ReactDOM.render(<Search />, document.getElementById('container'));

http://jsfiddle.net/kb3gN/15084/

Comments