Young L.
Young L.

Reputation: 1042

How to get value by radio selectButton in react

Hi I have this render method

return(
  <Form.Group className={'d-flex  justify-content-start'}>
      <Form.Label className={'mb-0 mr-2'}><b>Pohlavie:</b></Form.Label>
      <Form.Check
          type="radio"
          label="Muž"
          name="formHorizontalRadios"
          id="formHorizontalRadios1"
          className={'mr-2'}
      />
      <Form.Check
          type="radio"
          label="Žena"
          name="formHorizontalRadios"
          id="formHorizontalRadios2"
      />
  </Form.Group>
)

I am using react bootstrap Form.Check radio type component. Now From parrent i am getting object via props which have user.gender atribute (1 or 0) how i could connect this radioselect with gender attribute via state or somethin? Like when i select girl i have to change user.gender to 1 and also i have to make one of these radioselects default checked if value of user.gender is not null... How can i do that please?

Upvotes: 1

Views: 169

Answers (1)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

You need to attach onChange of your radio buttons to the callback that will modify your state:

const { useState } = React,
      { render } = ReactDOM,
      { Form } = ReactBootstrap,
      rootNode = document.getElementById('root')

const App = () => {
  const [gender, setGender] = useState()
  return (
  <Form.Group className={'d-flex  justify-content-start'}>
      <Form.Label className={'mb-0 mr-2'}><b>Pohlavie:</b>{gender && `(${gender})`}</Form.Label>
      <Form.Check
        type="radio"
        label="Muž"
        name="formHorizontalRadios"
        id="formHorizontalRadios1"
        className={'mr-2'}
        onChange={() => setGender('male')}
        />
      <Form.Check
        type="radio"
        label="Žena"
        name="formHorizontalRadios"
        id="formHorizontalRadios2"
        onChange={() => setGender('female')}
       />
</Form.Group>
  )
  
}

render (
  <App />,
  rootNode
)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"></script><div id="root"></div>

Upvotes: 1

Related Questions