InterviewSolution
| 1. |
How to pass data between sibling components using React router? |
|
Answer» Passing data between sibling components of React is possible using React Router with the help of history.push and match.params. In the code given below, we have a PARENT component AppDemo.js and have two Child Components HomePage and AboutPage. Everything is kept inside a Router by using React-router ROUTE. It is also having a route for /about/{params} where we will pass the data. import React, { Component } from ‘react’;class AppDemo extends Component {render() { return ( <Router> <div className="AppDemo"> <ul> <li> <NavLink to="/" activeStyle={{ color:'blue' }}>Home</NavLink> </li> <li> <NavLink to="/about" activeStyle={{ color:'blue' }}>About </NavLink> </li> </ul> <Route path="/about/:aboutId" component={AboutPage} /> <Route path="/about" component={AboutPage} /> <Route path="/" component={HomePage} /> </div> </Router> );}}export default AppDemo;The HomePage is a functional component with a button. On button CLICK, we are using PROPS.history.push(‘/about/’ + data) to programmatically NAVIGATE into /about/data. export default function HomePage(props) { const handleClick = (data) => { props.history.push('/about/' + data); }return ( <div> <button onClick={() => handleClick('DemoButton')}>To About</button> </div>)}Also, the functional component AboutPage will obtain the data passed by props.match.params.aboutId. export default function AboutPage(props) {if(!props.match.params.aboutId) { return <div>No Data Yet</div>}return ( <div> {`Data obtained from HomePage is ${props.match.params.aboutId}`} </div>)}After button click in the HomePage the page will look like below: |
|