Home  >  Q&A  >  body text

Solve the problem of getting undefined in React routing attributes

<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>
P粉696891871P粉696891871455 days ago548

reply all(2)I'll reply

  • P粉806834059

    P粉8068340592023-08-15 10:22:12

    You are passing props to your <Route/> component.

    <Route
      path="/contacts"
      loading={loading}
      contacts={getContacts}
      element={<Contacts />}
    />

    But you should pass them to your actual <Contacts/>Component

    <Route
      path="/contacts"
      element={<Contacts loading={loading} contacts={getContacts} />}
    />

    reply
    0
  • P粉852578075

    P粉8525780752023-08-15 09:54:15

    Try putting the state variable directly into the child element:

    <Route path='/contacts' element={<Contacts loading={loading} contacts={getContacts}/>} />

    reply
    0
  • Cancelreply