I am new to ReactJS. I am trying to figure out how to pass data from one page to another while using router. When I click on Add User button, I want to add the user and navigate back to home page.
I've searched the web for this and found examples where data is transferred from parent to child using props. But here I am using router. How can I find a way to do this?
index.js
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Home}>
<IndexRoute component={AllUsers}/>
</Route>
<Route path="/add" component={Add}/>
</Router>
, document.getElementById('root'));
Home.js:
class Home extends Component {
render() {
return (
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/add">Add</Link></li>
</ul>
</nav>
<div>
{this.props.children}
</div>
</div>
);
}
}
AllUsers.js
class AllUsers extends Component {
constructor(props) {
super(props);
this.state = {
headingsData: ["Name"],
rowsData: []
}
}
componentDidMount() {
this.setState({
rowsData: [{name: "Alex"}, {name: "Jack"}]
})
}
render() {
return (
<div className="allUsersContainter">
<h2>All users</h2>
<table border="1" className="tableComp">
<Headings headings={this.state.headingsData}/>
<tbody>
<Rows rows={this.state.rowsData}/>
</tbody>
</table>
</div>
);
}
}
class Headings extends Component {
render() {
let headings = this.props.headings.map((heading, i) => {
return (<th>{heading}</th>);
});
return (<thead><tr>{headings}</tr></thead>);
}
}
class Rows extends Component {
render() {
let rows = this.props.rows.map((row, i) => {
return (<tr key={i}><td>{row.name}</td></tr>);
});
return (<tbody>{rows}</tbody>);
}
}
export default AllUsers;
Add.js
class Add extends Component {
render() {
return (
<form>
<label>First Name:</label><input placeholder="Name" ref="name" required/><br/>
<button type="submit">Add user</button>
</form>
);
}
}
export default Add;