Home > Back-end >  What is the difference between these routes?
What is the difference between these routes?

Time:03-20

What is the difference between these Routes in react? Which one is correct and which one should I use?

<Routes>
          <Route exact path="/" element={<Home />} />
          <Route exact path="/about" element={<About />} />
          <Route exact path="/blog" element={<Blog />} />
</Routes>

or

<Routes>
          <Route exact path="/" component={Home} />
          <Route exact path="/about" component={About} />
          <Route exact path="/blog" component={Blog} />
</Routes>

CodePudding user response:

Both of them works almost same, but the one use case I can think of, for using element rather than the component(as most people do) is that you can pass props via the element method(element={<Home your_props={"yay I can pass props!"} />}).

So to summarize, there's no such correct or wrong way to do things in programming, it just depends upon your use case. If one was the wrong way, why would the developer keep it?

I hope I can help you decide which way to go.

CodePudding user response:

Both are correct, but see the below considerations.

1.In react-router-dom v6, 'Routes' is used instead of 'Switch'. The first code is thus the v6 format of react-router-dom.

2.In react-router-dom v5, there is no 'Routes'. you have to use 'Switch'. So the second code is v5 format of react router and is correct when you update the 'Routes' to 'Switch'.

Also in react-router-dom v6, you can easily pass the parameters as props to the child elements, like

<Route exact path="/about" element={<About msg={'message to child'}/>}  /> 
  • Related