What is the method to pass values between React pages?
In React, there are several ways to pass values between pages.
- You can pass values from a parent component to a child component by defining properties in the parent component and then passing them to the child component. The child component can then access the passed values through the props attribute.
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const value = 'Hello!';
return (
<ChildComponent value={value} />
);
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = (props) => {
return <div>{props.value}</div>;
};
export default ChildComponent;
- In the parent component, you can create a Context object and use the Provider component to wrap the child components wherever values need to be passed, then use the Consumer component in the child components to access the values.
// ValueContext.js
import React from 'react';
const ValueContext = React.createContext();
export default ValueContext;
// ParentComponent.js
import React from 'react';
import ValueContext from './ValueContext';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const value = 'Hello!';
return (
<ValueContext.Provider value={value}>
<ChildComponent />
</ValueContext.Provider>
);
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
import ValueContext from './ValueContext';
const ChildComponent = () => {
return (
<ValueContext.Consumer>
{value => <div>{value}</div>}
</ValueContext.Consumer>
);
};
export default ChildComponent;
- Using route parameters: When navigating between pages using routes, values can be passed through route parameters. By defining parameters in the route, you can access the parameter values in the target page using props.match.params.
// App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import ParentComponent from './ParentComponent';
import ChildComponent from './ChildComponent';
const App = () => {
return (
<Router>
<Route path="/" exact component={ParentComponent} />
<Route path="/child/:value" component={ChildComponent} />
</Router>
);
};
export default App;
// ParentComponent.js
import React from 'react';
import { Link } from 'react-router-dom';
const ParentComponent = () => {
const value = 'Hello!';
return (
<div>
<Link to={`/child/${value}`}>Go to Child Component</Link>
</div>
);
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = (props) => {
const value = props.match.params.value;
return <div>{value}</div>;
};
export default ChildComponent;
The above are several commonly used methods in React for passing values between pages, you can choose the method that suits your specific needs.