Update state of component from input and view it
Create class-based component
import React, {Component} from 'react';
class MyInput extends Component {
}
export default MyInput;
Implement render method
import React, {Component} from 'react';
class MyInput extends Component {
render(){
return(
<div>
<input/>
</div>
);
}
}
export default MyInput;
Write constructor and define state object:
import React, {Component} from 'react';
class MyInput extends Component {
constructor(props){
super(props);
this.state = {term: ''}
}
render(){
return(
<div>
<input/>
</div>
);
}
}
export default MyInput;
Make state be updated by value from input:
import React, {Component} from 'react';
class MyInput extends Component {
constructor(props){
super(props);
this.state = {field: ''}
}
render(){
return(
<div>
<input onChange={event => this.setState({field: event.target.value})}/>
</div>
);
}
}
export default MyInput;
Add reference to the state value in returned JSX:
import React, {Component} from 'react';
class MyInput extends Component {
constructor(props){
super(props);
this.state = {field: ''}
}
render(){
return(
<div>
<input onChange={event => this.setState({term: event.target.value})}/>
Your input: {this.state.term}
</div>
);
}
}
export default MyInput;
If you want to place some default value to the input field, we could make it a controlled field, using 'value' attribute, that referes to the state:
import React, {Component} from 'react';
class SearchBar extends Component {
constructor(props){
super(props);
this.state = {field: 'Some default value'}
}
render(){
return(
<div>
<input
value={this.state.term}
onChange={event => this.setState({field: event.target.value})}/>
Your input: {this.state.term}
</div>
);
}
}
export default MyInput;
If we have a parameter of function with name which eqauls the name of the state field, then we could just pass name of this field into the setState method:
constructor(props) {
super(props);
this.state = { videos: [] };
YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
this.setState({videos})
});
}