Reputation: 553
I have set up the routes for child components in the following parent component as sho
const AdminPage = props => (
<div>
//some other code
<Switch>
//some other routes
<Route
exact
path = path={props.match.url + "/flights/:flightNumber/passengers"}
component={PassengersPage}
/>
<Route exact path="/add-passenger" component={PassengerAddPage} />
</Switch>
</div>
);
export default AdminPage;
The following is the PassengersPage child component
import { Redirect } from "react-router-dom";
class PassengersPage extends React.Component {
state = {
redirectToAddPassengerPage: false
};
render() {
return (
<>
{this.state.redirectToAddCoursePage && <Redirect to="add-passenger" />}
//some presentational JSX
<button
style={{ marginBottom: 20 }}
className="btn btn-primary add-course"
onClick={() => {
this.setState({ redirectToAddPassengersPage: true });
}}
>
Add Passenger
</button>
</>
);
}
}
But nothing happens on button click. There is no error logs in console as well. Please help.
Upvotes: 0
Views: 129
Reputation: 2227
You are updating redirectToAddPassengersPage
on state but checking condition on redirectToAddPassengersPage
.
Try Updating your code like below
{this.state.redirectToAddPassengerPage && <Redirect to="/add-passenger" />}
Upvotes: 1
Reputation: 9652
Try using push method of history. Also Try extracting the click to setting the state, and on the call back use push to redirect to your necessary path.
clickHandler = () => {
this.setState({ redirectToAddPassengersPage: true },
() => {
this.props.history.push("/add-passenger");
})
}
Or going with your approach try passing push={true} . Something like
<Redirect to="/add-passenger" push={true}/>
Upvotes: 1
Reputation: 5957
You have two states, one of which controls the Redirect but it's not set in the button click:
class PassengersPage extends React.Component {
state = {
redirectToAddPassengerPage: false
};
render() {
return (
<>
// This next line needs to be changed to 'redirectToAddPassengersPage'
{this.state.redirectToAddPassengersPage && <Redirect to="add-passenger" />}
<button
style={{ marginBottom: 20 }}
className="btn btn-primary add-course"
onClick={() => {
this.setState({ redirectToAddPassengersPage: true });
}}
>
Add Passenger
</button>
</>
);
}
}
Upvotes: 1