3

Need to create radio buttons for Title (Mr. & Ms.) using react and the ref attribute.

Code for Class(Omitting the useless part):-

getTitle () {
// how could I get the selected title value here
var title = this.refs. ??;
},

render () {
   return (
       <div className='input-wrap'>
                        <label className='label'>
                            Mr.
                        </label>
                        <input  className='input'
                                type='radio'
                                ref= 'title'
                                name='user_title'
                                value='Mr.'
                                selected />

                        <label className='label'>
                            Ms.
                        </label>
                        <input  className=input'
                                type='radio'
                                ref= 'title'
                                name='user_title'
                                value='Ms.' />
                    </div>

      )
     }

Question:- How could I get the selected Title value in getTitle() ?

1 Answer 1

4

You can do it without refs.

class Radio extends React.Component{
    constructor(){
        super();
        this.state = {
            inputValue : ''
        }

    }

    change(e){
        const val = e.target.value;
        this.setState({
            inputValue : val
        })
    }
    render(){
        return <div>
                <label>MR<input type="radio" name="name" onChange={this.change.bind(this)} value="MR"/></label>
                <label>MS<input type="radio" name="name" onChange={this.change.bind(this)} value="MS"/></label>
                <br/>
                <h2>Value : {this.state.inputValue}</h2>
        </div>
    }
}

React.render(<Radio/>, document.getElementById('container'))

Fiddle example is here

I hope it will help you !

Thanks!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.