Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  184] [ 3]  / answers: 1 / hits: 74331  / 7 Years ago, tue, november 21, 2017, 12:00:00

I am new to react. How to render a component only after clicking a button in react?



Here in my case on clicking a button I have to display a table which displays the data from the database.



I have attached my code below for your reference, the first component is the button component and below that you can find the components for the table.



Also I would like to know how to refresh a component on clicking a button without refreshing the entire page.



var Button = React.createClass({
render: function () {
return (
<button type=button>Display</button>

); }
});

var EmployeeRow = React.createClass({

render: function () {
return (
<tr>
<td>{this.props.item.EmployeeID}</td>
<td>{this.props.item.FirstName}</td>
<td>{this.props.item.LastName}</td>
<td>{this.props.item.Gender}</td>
</tr>

);
}
});

var EmployeeTable = React.createClass({

getInitialState: function(){

return{
result:[]
}
},
componentWillMount: function(){

var xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = function () {
var response = JSON.parse(xhr.responseText);

this.setState({ result: response });

}.bind(this);
xhr.send();
},
render: function(){
var rows = [];
this.state.result.forEach(function (item) {
rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
});
return (
<Button />
<table className=table>
<thead>
<tr>
<th>EmployeeID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>

);
} });

ReactDOM.render(<EmployeeTable url=api/Employee/GetEmployeeList />,
document.getElementById('grid'))

More From » asp.net-mvc

 Answers
24

I've set up a sandbox to showcase how you can do this.



In essence:




  1. Initialise state with a boolean set to false

  2. Render the component conditionally based on this boolean; so initially the component will now show up on the DOM

  3. On some action (onClick), setState on the boolean to true

  4. The component will re-render since the state changed and will now show the hidden component (since the boolean has been set to true)


[#55878] Friday, November 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;