Answer the question
In order to leave comments, you need to log in
How to clear form after execution?
There is a component:
//Add.jsx
export default React.createClass({
handleFilmAdd() {
var title = ReactDOM.findDOMNode(this.refs.addTitle).value,
year = ReactDOM.findDOMNode(this.refs.addYear).value,
format = ReactDOM.findDOMNode(this.refs.addFormat).value,
actors = ReactDOM.findDOMNode(this.refs.addActors).value;
var item = {
"id": Date.now(),
"Title": title,
"ReleaseYear": year,
"Format": format,
"Stars": actors
};
console.log(item)
this.props.onFilmAdd(item)
},
render() {
return (
<div>
<input
defaultValue=''
placeholder='Title'
ref='addTitle'
/>
<input
defaultValue=''
placeholder='Release Year'
ref='addYear'
/>
<input
defaultValue=''
placeholder='Format'
ref='addFormat'
/>
<textarea
defaultValue=''
placeholder='Actors'
ref='addActors' ></textarea>
<button onClick={this.handleFilmAdd}>Add</button>
</div>
);
}
});
//App.jsx
handleFilmAdd(newFilm) {
var newFilms = this.state.displayedFilms.slice();
newFilms.unshift(newFilm);
this.setState({ displayedFilms: newFilms})
},
render() {
return (
<Add onFilmAdd={this.handleFilmAdd}/>
)}
Answer the question
In order to leave comments, you need to log in
Store changes to form elements in the state of the child component, and then just post the state and clear it afterwards:
function getDefaultState() {
return {
title: '',
year: '',
format: '',
actors: ''
};
}
export default React.createClass({
handleFilmAdd() {
this.props.onFilmAdd({
id: 'some_id',
...this.state
});
this.setState(getDefaultState());
},
handleChange(field, value) {
this.setState({
[field]: value
});
}
render() {
return (
<div>
<input
value={this.state.title}
onChange={this.handleChange.bind(this, 'title')}
placeholder='Title'
ref='addTitle'
/>
<input
value={this.state.year}
onChange={this.handleChange.bind(this, 'year')}
placeholder='Release Year'
ref='addYear'
/>
<input
value={this.state.format}
onChange={this.handleChange.bind(this, 'format')}
placeholder='Format'
ref='addFormat'
/>
<textarea
value={this.state.actors}
onChange={this.handleChange.bind(this, 'actors')}
placeholder='Actors'
ref='addActors'>
</textarea>
<button onClick={this.handleFilmAdd}>Add</button>
</div>
);
}
});
To generate an id, I use the node-uuid
library.
For example:
import { v4 } from 'node-uuid'
...
const myId = v4()
...
After Date.now() next in line is:
uuid: function () {
var i, random;
var uuid = '';
for (i = 0; i < 32; i++) {
random = Math.random() * 16 | 0;
if (i === 8 || i === 12 || i === 16 || i === 20) {
uuid += '-';
}
uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random))
.toString(16);
}
return uuid;
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question