Reputation: 75
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.
Upvotes: 2
Views: 294
Reputation: 870
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.
Upvotes: 1
Reputation: 95
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.
Upvotes: 2
Reputation: 484
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;
Upvotes: 2