InterviewSolution
| 1. |
How to pass data between sibling components using React router? |
|
Answer» We can pass data between React sibling components using React Router using history.push and match.params. Let look into the code. We have a Parent component APP.js. We have two CHILD Components HomePage and AboutPage. Everything is inside a Router from React-router Route. We also have a route for /about/{params}. This is where we will pass the data. import React, { Component } from ‘react’; class App extends Component { render() { return ( <Router> <div className="App"> <ul> <li> <NavLink to="/" activeStyle={{ color:'green' }}>Home</NavLink> </li> <li> <NavLink to="/about" activeStyle={{ color:'green' }}>About </NavLink> </li> </ul> <Route PATH="/about/:aboutId" component={AboutPage} /> <Route path="/about" component={AboutPage} /> <Route path="/" component={HomePage} /> </div> </Router> ); } } EXPORT default App;The HomePage is a simple FUNCTIONAL component, which have a button. On clicking the button we are using props.history.push(‘/about/’ + data) , which is used to programatically navigate to /about/data export default function HomePage(props) { const handleClick = (data) => { props.history.push('/about/' + data); } return ( <div> <button onClick={() => handleClick('Nabendu')}>To About</button> </div> ) }The AboutPage is also a simple functional component, which gets the passed data by props.match.params.aboutId export default function AboutPage(props) { if(!props.match.params.aboutId) { return <div>No Data Yet</div> } return ( <div> {`Data from HomePage ${props.match.params.aboutId}`} </div> ) }The Page after clicking on the button in the HomePage looks like below. |
|