In these example form components are react uncontrolled components.
It's best practice using controlled input (value+onChange. https://reactjs.org/docs/forms.html)
Example 1: implement componentDidUpdate method
class Form extends Component {
submit = (e) => {
e.preventDefault();
var user = Object.keys(this.refs).reduce( (obj, k) =>{
obj[k] = this.refs[k].value;
this.refs[k].value = '';
return obj;
}, {} );
this.props.onSubmit(user);
}
onChange = ({target:el}) => el.value = el.value.toUpperCase();
render() {
return (
);
}
componentDidUpdate(){
const {user} = this.props;
this.refs.name.value = user.name;
this.refs.surname.value = user.surname;
}
}
Example 2: use defaultValue
class Content6 extends Component {
state = {
formCfg: {name:'', cities:[]},
submittedData: {}
}
dataList = [
{name:'Pippo', cities:['Milan', 'Rome', 'Palermo'], isMale:true, defaultCity:'Rome' },
{name:'Tina', cities:['Torino', 'Genova', 'Pavia'], isMale:false},
{name:'Pino', cities:['Venice', 'Padova', 'Firenze'], isMale:true}
]
onClick = (formCfg) => this.setState({formCfg});
onSave = (submittedData) => this.setState({submittedData});
render() {
const {formCfg, submittedData} = this.state;
return (
click item to fill form:
{this.dataList.map( (cfg, i)=>(
this.onClick(cfg)}
style={{cursor:'pointer', backgroundColor:'#CCC', margin:2}}>
{JSON.stringify(cfg)}
))}
Submitted data: {JSON.stringify(submittedData)}
);
}
}
//stateless component
class FormSL extends Component {
onSubmit = ({name: {value:name}, city:{value:city},isMale:{checked:isMale}}) =>
this.props.save({name, city, isMale});
render() {
const {name, cities,isMale, defaultCity} = this.props;
return ( );
}
}