Search code examples
reactjsformsradio-button

Radio ref on react


I have radio input use want to use ref to show the result on console.

I always get second value even when I have choose the first one. This is the constructor

this.inputKelamin = React.createRef();

and rendered like this

<div>
        Jenis Kelamin :
        <input name="kelamin" type="radio" value="laki - laki" ref={this.inputKelamin}/>
        Laki - laki
        <input name="kelamin" type="radio" value="perempuan" ref={this.inputKelamin}/>
        Perempuan
      </div>

onSubmit, I put it like this via console :

alamat : ${this.inputAlamat.current.value}

the result is always "perempuan" This is not for production, just a learning purpose, thank you


Solution

  • You're using same ref for both the element, second ref={this.inputKelamin} overrides the first one and it always points to the second radio button.

    From official docs

    Refs provide a way to access DOM nodes or React elements created in the render method.

    You should create 2 different refs for both inputs.

    And you're checking the wrong property here

    this.inputAlamat.current.value
    

    value will always be the attribute value you gave value="perempuan".

    In case of radio you should look at the checked property, which tells you whether it was selected

    this.inputKelamin.current.checked
    

    Also, you might want to look at controlled and un-conntrolled components