Top React Routing Questions & Answers

This Article contains Question of React Router V5 and V6

React Router v6

πŸ’‘ What are route matching components?

Switch and Route are the two route matching components. When a <Switch> is rendered, it searches through its children <Route> elements to find one whose path matches the current URL. When it finds one, it renders that <Route> and ignores all others. If no <Route> matches, the <Switch> renders nothing (null).

πŸ’‘ Is it ok to put <Route path=”/”> at first & last index in Switch?

<Route path> matches the beginning of the URL, not the whole thing.
So a <Route path="/"> will always match the URL. Because of this, we typically put <Route> last in <Switch>.
If want to put it anywhere then a possible solution is to use <Route exact path="/"> which does match the entire URL.

πŸ’‘ What is Link & NavLink in React Router?

React Router provides a <Link> component to create links in your application. Wherever you render a <Link>, an anchor will be rendered in your HTML document.
The <NavLink> is a special type of <Link> that can style itself as β€œactive” when its to prop matches the current location.

<Link to="/">Dashboard</Link>
// <a href="/">Dashboard</a>

<NavLink to="/home" activeClassName="hurray">

πŸ’‘ How can we render components with React Route?

There is a total of three ways provided by React Router to render components.

  1. React Component props
  2. React render function
  3. React children props.

Note: The recommended method of rendering something with a is to use children elements.

πŸ’‘ What is the difference between react Router component way and render function way?

When you use component, the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component for every render. Instead of just upgrading the old component, the existing component is unmounted and the newly created component is mounted.

Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop function has access to all the same route props (match, location, and history) as the component render prop.

    <Route path="/user/:username" component={User} />
    <Route path="/home" render={() => <div>Home</div>} />

πŸ’‘ Can we use component and render both Route method at once?

<Route component> takes precedence over <Route render>, so don’t use both in the same <Route>.

πŸ’‘ Explain all attributes of BrowserRouter?

A <Router> that uses the HTML5 history API (pushState, replaceState, and the popstate event) to keep your UI in sync with the URL.

  <App />

basename – The base URL for all locations.
getUserConfirmation – A function to use to confirm navigation.
forceRefresh – If true the router will use full-page refreshes on every page navigation.
keyLength = The length of location.key. Defaults to 6.

<BrowserRouter basename="/calendar"
    getUserConfirmation={(message, callback) => {
        // this is the default behavior
        const allowTransition = window.confirm(message);
    <Link to="/today" /> // renders <a href="/calendar/today">
    <Link to="/tomorrow" /> // renders <a href="/calendar/tomorrow">

πŸ’‘ What are HashRouter and MemoryRouter?

<Router> that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

  <App />

Read here:

<Router> that keeps the history of your β€œURL” in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.

  initialEntries={["/one", "/two", { pathname: "/three" }]}
  <App />

Read here:

πŸ’‘ What is the purpose of “exact”?

When true, will only match if the path matches the location.pathname exactly.

<Route exact path="/one">
  <About />
path       location.pathname      exact     matches?
/one /one/two true no
/one /one/two false yes

πŸ’‘ What is the strict property in Route?

When true, a path that has a trailing slash will only match a location.pathname with a trailing slash.

<Route strict path="/one/">
  <About />
path    location.pathname   matches?
/one/ /one no
/one/ /one/ yes
/one/ /one/two yes

πŸ’‘ What will happen with the below code?

<Route exact strict path="/one">
  <About />

strict can be used to enforce that a location.pathname has no trailing slash, but in order to do this both strict and exact must be true.

path    location.pathname   matches?
/one /one yes
/one /one/ no
/one /one/two no

πŸ’‘ What is Redirect?

Any time that you want to force navigation, you can render a <Redirect> . When it renders, it will navigate using its to prop.
Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack like server-side redirects (HTTP 3xx) do.

<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}

πŸ’‘ What are Route props?

All three render methods will be passed the same three route props

πŸ’‘ What all properties, the match object contains?

A match object contains information about how a matched the URL. match objects contain the following properties:

params – Key/value pairs parsed from the URL.
isExact – true if the entire URL was matched (no trailing characters)
path – The path pattern used to match. Useful for building nested <Route> s
url – The matched portion of the URL. Useful for building nested <Link> s

πŸ’‘ How to get params in react?

useParams hook returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

 <Route path="/users/:userId">
        <BlogPost />
 let { userId } = useParams();

πŸ’‘ How to upgrade from Router V5 to V6?

πŸ’‘ What are the features of React Router V6?

  • Switch Replaced with Routes.
  • Defining Component with element prop.
  • The exact Prop is not Needed Anymore
  • No Need to Install react-router-config Separately
  • useHistory is now useNavigate
  • activeStyle and activeClassName Props Removed From <NavLink>
  • Replace Redirect with Navigate

Read here full story –

πŸ’» Routes Structure of V6

      <Route path="/" element={<App />}>
        <Route index element={<Home />} />
        <Route path="teams" element={<Teams />}>
          <Route path=":teamId" element={<Team />} />
          <Route path="new" element={<NewTeamForm />} />
          <Route index element={<LeagueStandings />} />

πŸ’» NavLink code in V5 and V6

  style={{ color: 'black' }}
  activeStyle={{ color: 'blue' }}>

  style={({isActive}) => { color: isActive ? 'blue' : 'black' }}>

πŸ’» React Redirect Component in V6

// v5
<Route exact path="/latest-news">
    <Redirect to="/news">

// v6
<Route path="/latest-news" element={<Navigate replace to="/news">} />

πŸ’‘ React Router Authentication implement and Protected Routes in React Router V6?

Top React Routing Questions & Answers

βœ” React JS Interview Questions & Answers 2022 – Part 3

βœ” Top React JS Interview Questions and Answers – Part 2

βœ” React JS Interview Questions & Answers – Part 1

βœ” Higher Order Component with Functional Component | React JS

βœ” Create Custom QR Code Component using QR Code Styling in React JS

Top React Routing Questions & Answers

Leave a Reply

Your email address will not be published.