Routing

react interview question and answer, top react interview question, interview question react, interview question react js, react routing interview questions, react js routing interview questions, react-router interview questions, react routing, react routing questions

This Article contains Question of React Router V5 and V6

React Router v6
https://reactrouter.com/docs/en/v6/getting-started/overview


πŸ’‘ 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">
  Home
</NavLink>

react interview question and answer | react routing | react routing questions


πŸ’‘ 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 the 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 renders prop.

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


πŸ’‘ Can we use the component and render both Route methods 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.

<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App />
</BrowserRouter>

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"
    forceRefresh={true}
    keyLength={12}
    getUserConfirmation={(message, callback) => {
        // this is the default behavior
        const allowTransition = window.confirm(message);
        callback(allowTransition);
    }}
>
    <Link to="/today" /> // renders <a href="/calendar/today">
    <Link to="/tomorrow" /> // renders <a href="/calendar/tomorrow">
</BrowserRouter>


πŸ’‘ 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.

<HashRouter
  basename={optionalString}
  getUserConfirmation={optionalFunc}
  hashType={optionalString}
>
  <App />
</HashRouter>

Read here: https://v5.reactrouter.com/web/api/HashRouter

<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.

<MemoryRouter
  initialEntries={["/one", "/two", { pathname: "/three" }]}
  initialIndex={1}
  keyLength={12}
  getUserConfirmation={optionalFunc}
>
  <App />
</MemoryRouter>

Read here: https://v5.reactrouter.com/web/api/MemoryRouter


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

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

<Route exact path="/one">
  <About />
</Route>
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 />
</Route>
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 />
</Route>

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 />}
</Route>


πŸ’‘ 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 />
      </Route>
	  
 let { userId } = useParams();


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

https://reactrouter.com/docs/en/v6/upgrading/v5


πŸ’‘ 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 –
https://dev.to/arunavamodak/react-router-v5-vs-v6-dp0


πŸ’» Routes Structure of V6

<BrowserRouter>
    <Routes>
      <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 />} />
        </Route>
      </Route>
    </Routes>
  </BrowserRouter>


πŸ’» NavLink code in V5 and V6

/V5
<NavLink
  to="/news"
  style={{ color: 'black' }}
  activeStyle={{ color: 'blue' }}>
  Exchanges
</NavLink>

//V6
<NavLink
  to="/news"
  style={({isActive}) => { color: isActive ? 'blue' : 'black' }}>
  Exchanges
</NavLink>


πŸ’» React Redirect Component in V6

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

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


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

https://www.robinwieruch.de/react-router-authentication/

react interview question and answer, top react interview question, interview question react, interview question react js, react routing interview questions, react js routing interview questions, react-router interview questions, react routing, react routing questions

Leave a Reply

Your email address will not be published.