Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Match Miss

What is the advantage of using Match and Miss components from react-router over Router component? I cannot seem find any documentation about this in react-router docs.

My question spawns from looking at react-universally boilerplate, more exactly, by looking here: https://github.com/ctrlplusb/react-universally

like image 875
Dragos Rizescu Avatar asked Feb 21 '17 08:02

Dragos Rizescu


People also ask

How do I use match in react router 6?

To find the matched route in react-router v6 you need to use the matchPath function. You will need to store all your routes in a variable like an array. Then you can loop through all routes and use that function to find the matched route.

How do you use useRouteMatch in react dom v6 router?

When using React Router v5, it was possible to get the path (pattern) for that route using useRouteMatch . const { path } = useRouteMatch(); React Router v6 offers a similar hook, useMatch ; however this expects to receive the pattern you want to match against.


2 Answers

<Match> and <Miss> were components in the alpha release of React Router v4.

In the beta, <Match> has been renamed <Route> (and its props have changed so that pattern is now path and exactly is exact). The <Miss> component was removed entirely. Instead you should use a <Switch> statement, which will only render the first <Route> (or <Redirect>) that is matched. You can add a pathless component as the last child of the <Switch>'s routes and it will render when none of the preceding <Route>s match.

You can check out the API documentation for more details.

<Switch>
  <Route exact path='/' component={Home} />
  <Route path='/about' component={About} />
  // The following <Route> has no path, so it will always
  // match. This means that <NoMatch> will render when none
  // of the other <Route>s match the current location.
  <Route component={NoMatch} />
</Switch>
like image 200
Paul S Avatar answered Sep 18 '22 02:09

Paul S


And to add to the last post, you'll find this in react-router-dom. It's no longer in the react-router core library.

Here's a pattern I have found works for react routing. Same as previous posters, basically. You'll need to build the additional components included.

import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';

{/* Import your components here */}

class Root extends React.Component{
    render(){
        return(
             <Router>
                     <Switch>
                        <Route exact path='/' component={App} /> )} />
                        <Route path="/some-component"  component={SomeComponent} /> 
                        <Route component={NotFound}/>
                    </Switch>
             </Router>
        );
    }
 } 
        
render(<Root/>, document.querySelector('#main'));
like image 43
Hillsie Avatar answered Sep 20 '22 02:09

Hillsie