Redirect in React JS

Zainab Omar
2 min readJul 15, 2021

--

There are many different ways to redirect from page to page in React applications:

1. Redirect Component

We can redirect using <Redirect> component by importing it from “react- router-dom” library. This way works in both functional and class components.

2. Use history Hook

This way can be used inside functional components.

3. History prop

Every component that is an immediate child of the <Route> component receives history object as a prop. A common problem is if a component is not an immediate child to <Route> component, there is no history prop present. This way works in both functional and class components.

4. withRouter

withRouter is a function provided in the “react-router-dom” library that helps us access the history prop in components which are not immediate children to the <Route> components. This way works in both functional and class components.

after that we need to wrap our component with withRouter while exporting it.

That’s all for now — Thanks for reading and happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response