2

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.

Yun
  • 75
  • 6
  • there is no redirect action. The clicked method just returns a `````` that is not actually rendered. – Tituuss10 Nov 18 '19 at 11:12
  • When you run `renderRedirect`, it renders `` in your application to let `react-router` know where to redirect to, without this ``, it doesn't know so nothing happens – Duc Hong Nov 18 '19 at 11:13
  • Take a look at this answer: https://stackoverflow.com/questions/45089386/what-is-the-best-way-to-redirect-a-page-using-react-router . There are some nice examples that will help you. – Tituuss10 Nov 18 '19 at 11:14
  • I believe it is bad practice to try to use a component for rerouting on a ```onClick``` method. Try the ```this.props.history.push('/path')``` mentioned in the above post. – Tituuss10 Nov 18 '19 at 11:19

3 Answers3

2

try in this way :

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

const Home = () => {
  console.log('Home');
  constructor(props){
   this.state={
    isRedirect : false;
 }
}
  const renderRedirect = () => {
  if (this.state.isRedirect) {
    return (
     <Redirect to={{
      pathname: '/counter'
     }}
    />
   );
 }
}

  const clicked = () => {
    console.log('clicked');
    this.setState({
     isRedirect :true
    })
  }

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

export default Home;
Shashwat Prakash
  • 434
  • 5
  • 14
2

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.

dilanMD
  • 95
  • 2
  • 12
1

Clicked function is only returning Redirect component. But it is not getting appended in the JSX anywhere. Triggering it is one part and appending it is second. Commenting out renderRedirect means you are missing the second step.

Sunny Prakash
  • 772
  • 1
  • 8
  • 13