'How to provide dynamic content pages in react?
After submitting a form I need to display a success page. It's content is determined by the form values and it consists of headline, static text and a form value. In the end 5 different success pages are possible. How can I best provide the data in a separate success page? Do I need 5 different success pages or is there dynamic solution possible?
Routes
<Route path="/form" element={<MyForm/>} />
<Route path="/success" element={<SuccessPage/>} />
success page templates
<h1> Headline A </h1>
<p> Text A <p>
<span> {form value name} </span>
<h1> Headline B </h1>
<p> Text B <p>
<span> {form value name} </span>
Solution 1:[1]
There are multiple solutions to this problem.
- You can put the form values on the query string. Then use that to display content.
import { useLocation } from 'react-router-dom';
// http://localhost:4000/success?valueA=101
const SuccessGenericComponent = () => {
const search = useLocation().search;
const valueA = new URLSearchParams(search).get("valueA");
console.log(valueA); //101
return (
<h1> Headline A </h1>
<p> Text A <p>
<span> {valueA} </span>
)
}
- You can use a state management library like Redux, React.Context, or even just your localstorage to handle the state of your form and access it in a different component. This will involve an initial setup though.
Solution 2:[2]
You can use generic component for this usecase, as your template data is same, No need for different pages.
You can add conditional rendering to differenciate the page or define a type of page you need from service and display based on that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KnowYourElements |
| Solution 2 | Osama Malik |
