I've done exactly as pointed by the most upvoted answer on this post show or hide element in react.js to show and hide my elements.
But it works only on first button click. If I input another value in my form and resubmit it then the data remains the same as before. It's never going into "Results" second time onwards. What am I doing wrong?
This is the code from that link above:
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'));
EDIT new code:
module.exports = React.createClass({
getInitialState: function() {
console.log("in getInitialState");
return { showResults: false };
},
onClick: function(e) {
e.preventDefault();
data = null;
console.log("in onClick");
ticId = ReactDOM.findDOMNode(this.refs.ticketid).value;
if (this.state.showResults == true) // second button click (update data)
{
var newdata = "";
$.ajax({
url: 'http://localhost:x/' + 'tickets',
type: 'GET',
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic " + btoa(u + ":" + p)
},
data: {ticketid: ticId},
success: function(result) {
newdata = result.results;
}
});
if(newdata)
{
console.log(newdata); //SUCCESS: getting new data here
}
this.state.data = newdata; //FAIL: state not getting refreshed
}
else
{
this.setState({ showResults: true });
}
},
render: function() {
return (
<div className='someclass'>
<form className="someForm" onSubmit={this.onClick}>
<input type="text" placeholder = "Enter ticket Id" ref="ticketid" />
<input type="submit" value="Find!!" />
{ this.state.showResults ? <Results /> : null }
</form>
</div>
);
}
});