Ad

How To Redirect In React.js

- 1 answer

I would like to ask you about redirecting in React.js.

Below is modified thing of Home.js in https://github.com/supasate/connected-react-router/blob/master/examples/basic/src/components/Home.js

(It's NOT my private GitHub Repo! It's open source library)

import React, { useState } from 'react'
import { Redirect } from 'react-router-dom'

const Home = () => {
  console.log('Home');


  const renderRedirect = () => {
    return <Redirect to={{
      pathname: '/counter'
    }} />
  }

  const clicked = () => {
    console.log('clicked');
    return <Redirect to={{
      pathname: '/counter'
    }} />
  }

  return (
    <div>
      Home
      {/* {renderRedirect()} */}
      <button onClick={() => clicked()}>counter</button>
    </div>
  )
}

export default Home

The function renderRedirect() is commented in tag now. And if I uncomment this function, this function and redirecting work well.

But when I clicked a button in tag, redirecting won't work. Why does redirecting have no effect?

Thanks for reading.

Ad

Answer

There is no redirecting scenario in the react. Instead it just re render the particular component. That's why it is recognized as virtual DOM. In your scenario the component is not re rendering.

Ad
source: stackoverflow.com
Ad