I want to build a basic app. I have a Questions page and I keep the answers of the questions in answers array. After the test I want to send user to Results page with Link for see the score. So I need the use answers array in the Results component but when I try this I just get an empty array. It's obvious there is a mistake in my Routing or something. I cropped to parts that I thougt unnecessary. If you need more info about that just let me know. Here is my App.js
function App() {
const [answers,setAnswers]=React.useState();
return (
<div className="App">
<Router>
<Routes>
<Route exact path="/" element={<Homepage />} />
<Route exact path="/questions" element={<Questions />} />
<Route exact path='/results' element={<Results state={answers}/>} />
</Routes>
</Router>
</div>
);
}
export default App;
Questions.js
function Questions() {
const [answers, setAnswers] = React.useState([]);
return(
<div>
<h1>Questions</h1>
<Link to={{pathname:"/results"}} state={answers}>
Go to Results
</Link>
</div>
)
}
Results.js
function Results(props){
const [answers, setAnswers] = useState([props.state]);
console.log(answers)
return(
<div>
Result Page
</div>
)
}
CodePudding user response:
First of all, don't add data from props to state, it will only make it harder
https://codesandbox.io/s/modern-glitter-546kuv?file=/src/App.js
Pass state to the components in App
export default function App() {
const [answers, setAnswers] = React.useState([]);
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route
exact
path="/"
element={<Questions setAnswers={setAnswers} />}
/>
<Route
exact
path="/results"
element={<Results answers={answers} />}
/>
</Routes>
</BrowserRouter>
</div>
);
}
Show answers in Results
function Results({ answers }) {
return (
<div>
Result Page
{answers.map((q) => (
<p>{q}</p>
))}
</div>
);
}