I am new in react. I write react with typescript without redux. In my sample project i want after submit form, change route, but i can not do this. following code is my try. how can I change route in fetch then function? why this value is undefined!
import * as React from 'react';
import 'isomorphic-fetch';
import { ReactRouter } from 'react-router-dom';
export interface Props {router?: ReactRouter.History.History;}
interface State {name: string;}
export class CreateItem extends React.Component<Props, State> {
private input: HTMLInputElement;
constructor(props: Props) {
super(props);
this.state = {name: ""};
this.input = null;
}
public render(){
return <form onSubmit={this.handleSubmit} className="form-horizontal">
<div className="form-group">
<label className="col-sm-2 control-label">Date</label>
<div className="col-sm-5">
<input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} className="form-control">
</input>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-5">
<button type="submit" className="btn btn-default" disabled={!this.state.name}>ADD</button>
</div>
</div>
</form>;
}
private handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
event.preventDefault();
if (this.state.name) {
var form = new FormData();
form.append('name', name);
fetch('/api/SampleData/', { method: 'POST', body: form })
.then(function (res) {
this.props.history.push('/fetchdata');// **this code not work**
});
this.setState({
name: ""
});
}
}
private handleInputChange = (event: React.FormEvent<HTMLInputElement>): void => {
const target = event.target;
const name = target["name"];
this.setState({
[name]: (event as any).target.value
})
}
}