Reputation: 113385
I have a form:
<form onSubmit={this.onSubmit}>
<input ref="name" type="text" />
...
<select ref="pet">
<option>Dog</option>
<option>Cat</option>
</select>
</form>
In another place, I have a different form, with different inputs, but the same select
. I could simply bindly copy the code from the first one, but I don't want to.
I want to make a component. In terms of UI, I know it would work. However, I have no idea how to access this.refs.pet.value
in that case:
<form onSubmit={this.onSubmit}>
<input ref="name" type="text" />
...
<PetsSelect ??????? />
</form>
How to access the value of the select
box from the component, in its parent (form)?
Upvotes: 0
Views: 345
Reputation: 39
class FormComponent extends React.Component{
constructor(props){
super(props)
this.state = {selected: null,
...
}
}
selectPet(e){
this.setState({selected: e.target.value})
}
render(){
return (<form onSubmit={this.onSubmit}>
<input ref="name" type="text" />
...
<PetsSelect onSelect={this.selectPet.bind(this)} />
</form>)
}
}
class PetsSelect extends React.Component{
constructor(props){
super(props)
}
render(){
return (<select onChange={this.props.onSelect}>
<option value='dog'>Dog</option>
<option value='cat'>Cat</option>
</select>)
}
}
Upvotes: 0
Reputation: 26165
very quick example on composing
class PetsSelect extends React.Component {
get value(){
return this.state.value
}
handleChange(key, value){
this.setState({[key]: value})
this.props.onChange && this.props.onChange(key, value)
}
constructor(props){
super(props)
this.state = { value: props.value || '', name: '' }
}
render(){
// add the name etc and then you can handleChange('name', ...)
// or make it more DRY
return <div>
<select
ref={select => this.select = select}
value={this.state.value}
onChange={e => this.handleChange('value', e.target.value)}>
<option value=''>Please select</option>
<option value='dog'>Dog</option>
<option value='cat'>Cat</option>
</select>
</div>
}
}
class Form extends React.Component {
handleSubmit(e){
e.preventDefault()
console.log(this.pets.value)
}
render(){
// this.pets becomes the instance of the PetsSelect class.
return <form onSubmit={e => this.handleSubmit(e)}>
<PetsSelect ref={pets => this.pets = pets} />
<button type='submit'>try it</button>
</form>
}
}
ReactDOM.render(<Form />, document.getElementById('app'))
see here: https://codepen.io/anon/pen/WExepp?editors=1010#0. basically, you can either: onChange and get the value in the parent, or read the value of the child when needed.
keep in mind you said 'controlled' - i am not doing anything to keep props.value
with state.value
- and in uncontrolled, you'd use defaultValue
Upvotes: 2
Reputation: 7044
Just add ref like this <PetsSelect ref="petSelect"/>
and get value by this this.refs.petSelect.refs.pet.value
.
Upvotes: 0