Solve the problem of getting undefined in React routing attributes
P粉696891871
2023-08-14 14:56:23
<p>I want to send some properties (<code>loading</code> and <code>getContacts</code>) to a component in ReactJS. I'm using routing to get each path, but the result is undefined in the target component. How is this going? </p>
<pre class="brush:php;toolbar:false;">const App = () => {
const [getContacts, setContacts] = useState([]);
const [loading, setLoading] = useState(false);
return(
<div className='App'>
<Navbar/>
<Routes>
<Route path='/' element = {<Navigate to ="/contacts"/>}/>
<Route path='/contacts' loading= {loading} contacts= {getContacts} element= {<Contacts/>} />
<Route path="/contacts/add" element = {<AddContact/>}/>
<Route path = "/contacts/:contactId" element = {<ViewContact/>}/>
<Route path = "/contacts/edit/:contactId" element = {<EditContact/>}/>
<Route path="*" element={
<div className='text-light py-5'>
Not Found!
</div>}
/>
</Routes>
</div>
);
export default App;</pre>
<p>In Contact.jsx I have: </p>
<pre class="brush:php;toolbar:false;">const Contacts = ({ contacts, loading }) => {
return (
<>
<div>{contacts}</div>
<div>{loading}</div>
</>
);
};
export default Contacts;</pre>
<p>But they are all undefined. </p>
You are passing props to your
<Route/>
component.But you should pass them to your actual
<Contacts/>
ComponentTry putting the state variable directly into the child element: