patternjavascriptreactCritical
Show or hide element in React
Viewed 0 times
showreactelementhide
Problem
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 to use 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 (event) {
console.log(this.prop);
},
render: function () {
return (
);
}
});
var Results = React.createClass({
render: function () {
return (
Some Results
);
}
});
React.renderComponent( , document.body);
Solution
React circa 2020
In the
JSFiddle
React circa 2014
The key is to update the state of the component in the click handler using
JSFiddle
In the
onClick callback, call the state hook's setter function to update the state and re-render:const Search = () => {
const [showResults, setShowResults] = React.useState(false)
const onClick = () => setShowResults(true)
return (
{ showResults ? : null }
)
}
const Results = () => (
Some Results
)
ReactDOM.render(, document.querySelector("#container"))
JSFiddle
React circa 2014
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 (
{ this.state.showResults ? : null }
);
}
});
var Results = React.createClass({
render: function() {
return (
Some Results
);
}
});
ReactDOM.render( , document.getElementById('container'));
JSFiddle
Context
Stack Overflow Q#24502898, score: 841
Revisions (0)
No revisions yet.