Create TaskForm (P2)
C:\Users\Administrator\Desktop\reactypes\src\components\App.tsx
import React from 'react';
import { ITask } from './Task';
import TaskForm from './TaskForm';
interface IProps {
title ? : string;
}
interface IState {
tasks: ITask[];
}
class App extends React.Component < IProps, IState > {
constructor(props: IProps) {
super(props);
this.state = {
tasks: []
};
this.addANewTask = this.addANewTask.bind(this);
}
public addANewTask(task: ITask): void {
this.setState({
tasks: [...this.state.tasks, task]
});
}
render(): JSX.Element {
return (
<div>
<nav className="navbar navbar-light bg-light">
<a className="navbar-brand" href="/">{this.props.title}</a>
</nav>
<div className="container p-4">
<div className="row">
<div className="col-md-4">
<TaskForm addANewTask={this.addANewTask} />
</div>
</div>
</div>
</div>
);
}
}
export default App;
C:\Users\Administrator\Desktop\reactypes\src\components\TaskForm.tsx
import * as React from 'react';
import { ITask } from './Task';
interface ITaskFormProps {
addANewTask: (task: ITask) => void;
}
class TaskForm extends React.Component < ITaskFormProps, any > {
private titleInput = React.createRef < HTMLInputElement > ();
constructor(props: ITaskFormProps) {
super(props);
this.state = {
title: '',
description: '',
};
}
handleInputChange(e: React.ChangeEvent < HTMLInputElement | HTMLTextAreaElement > ) {
const { value, name } = e.target;
this.setState({
[name]: value
});
}
private getCurrentTimestamp(): number {
const date: Date = new Date();
return date.getTime();
}
handleNewTask(e: React.FormEvent < HTMLFormElement > ): any {
e.preventDefault();
const newTask: ITask = {
id: this.getCurrentTimestamp(),
title: this.state.title,
description: this.state.description,
completed: false
};
this.setState({ title: '', description: '' });
this.props.addANewTask(newTask);
}
render(): JSX.Element {
return (
<div className="card card-body">
<form onSubmit={e => this.handleNewTask(e)}>
<div className="form-group">
<input onChange={e => this.handleInputChange(e)} type="text" placeholder="Add A Task" name="title" value={this.state.title} className="form-control" autoFocus/>
</div>
<div className="form-group">
<textarea onChange={e => this.handleInputChange(e)} name="description" className="form-control" value={this.state.description}></textarea>
</div>
<button type="submit" className="btn btn-primary btn-block">
Save
</button>
</form>
</div>
)
}
}
export default TaskForm;
C:\Users\Administrator\Desktop\reactypes\src\components\Task.tsx
export interface ITask {
id ? : number;
title: string;
description: string;
completed: boolean;
}
Last updated
Was this helpful?