3 agosto 2018

React prefill input/form

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 ( <form onSubmit={this.submit}> <div className="form-group"> <input type="text" ref="name" className="form-control" placeholder = "name"/> </div> <div className="form-group"> <input type="text" ref="surname" onChange={this.onChange} className="form-control" placeholder="surname" /> </div> <button type="submit" className="btn btn-primary">add</button> </form> ); } 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 ( <div> <p>click item to fill form:</p> {this.dataList.map( (cfg, i)=>( <div key={i} onClick={(ev)=>this.onClick(cfg)} style={{cursor:'pointer', backgroundColor:'#CCC', margin:2}}> {JSON.stringify(cfg)} </div>))} <div> <p>Submitted data: {JSON.stringify(submittedData)}</p> </div> <div><FormSL {...formCfg} save={this.onSave}/></div> </div> ); } } //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 ( <form> <input ref='name' defaultValue={name} type="text" className="form-control" /><br/> <select ref='city' name="" id="" className="form-control" size={cities.length+1}> <option value=''>[select city]</option> {cities.map((city)=><option key={city} value={city.toUpperCase()} selected={defaultCity===city}> {city} </option> ) } </select><br/> <input ref="isMale" type="checkbox" defaultChecked={isMale} /> isMale<br/> <button type="button" onClick={() => this.onSubmit(this.refs)} >submit</button> </form> ); } }

Nessun commento:

Posta un commento