skip to Main Content

I want to send some properties (loading and getContacts) to a Component in reactjs . I use routes in order to get each path, but the result in the target component is undefined. Whats wrong with it?

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;

In Contact.jsx I have:

const Contacts = ({ contacts, loading }) => {

    return (
        <>
            <div>{contacts}</div>
            <div>{loading}</div>
        </>
    );
};

export default Contacts;

But both of them are undefined.

2

Answers


  1. Try placing the state variables directly into the children element :

    <Route path='/contacts' element={<Contacts loading={loading} contacts={getContacts}/>} />
    
    Login or Signup to reply.
  2. You are passing the props to your <Route/> component.

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

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

    <Route
      path="/contacts"
      element={<Contacts loading={loading} contacts={getContacts} />}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search