I am working on React with Typescript. "Redirect" doesn't seem to work for me. I don't know what the problem is.
import * as React from "react"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import store from "./ToDoStore"
import { Redirect} from "react-router-dom";
export class AddTodo extends React.Component {
refs: {
name: (HTMLInputElement);
description: (HTMLInputElement);
}
addTodo() {
store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
alert("Task added successfully");
<Redirect to="/home" push/>
}
render() {
return (
<div id="addtodo">
<TextField
label='Add Todo' ref="name"
/>
<br />
<TextField
label='Add Description' ref="description"
/>
<br />
<PrimaryButton text="Add" onClick={this.addTodo.bind(this)} />
</div>
)
}
}
This is not a typescript related issue. This is improper usage of <Redirect/>
. You are trying to use a JSX component in a callback; this won't work. What you need to do is have some state change when a todo is added and conditionally render the <Redirect/>
component when that state is true.
Try the below refactoring.
export class AddTodo extends React.Component {
constructor(props) {
super(props);
this.state = {
shouldRedirect: false
};
this.addTodo = this.addTodo.bind(this);
}
refs: {
name: (HTMLInputElement);
description: (HTMLInputElement);
}
addTodo() {
store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
alert("Task added successfully");
this.setState({ shouldRedirect: true });
}
render() {
return (
<div id="addtodo">
{
this.state.shouldRedirect ?
<Redirect to="/home" push/> :
<div>
<TextField
label='Add Todo' ref="name"
/>
<br />
<TextField
label='Add Description' ref="description"
/>
<br />
<PrimaryButton text="Add" onClick={this.addTodo} />
</div>
}
</div>
);
}
}
For react-router-dom
v6 you will need to use <Navigate />
instead of <Redirect />
ex.
// use
<Navigate to="home" />
// not
<Redirect to="home" />
See: this stackoverflow answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With