Home > database >  How I get the value inside of a bullet point in react?
How I get the value inside of a bullet point in react?

Time:05-08

            <br />
            <input type='radio' name='delivery_stat' id='delivery' ></input>
            <label htmlFor="pending" >Pending delivery</label>
            <br />
            <input type='radio' name='delivery_stat' id='delivery' ></input>
            <label htmlFor="done" >Complete delivery</label>

enter image description here

There are two options. Either pending delivery or complete delivery. If user select pending delivery then how do I get that value in my code in react.

CodePudding user response:

Firstly, you need to define useState for the selected value from radio buttons

const [selectedValue, setSelectedValue] = React.useState() 

And then, you should have a click event to handle radio selection

//state will be updated according to your radio selection
const handleChange = (e) => {
   setSelectedValue(e.target.value)
}

Lastly, you should add value='Pending delivery' and onChange={handleChange} to radio elements

<input type='radio' name='delivery_stat' id='delivery' value='Pending delivery' onChange={handleChange}/>

Full possible change

const App = () => {
    const [selectedValue, setSelectedValue] = React.useState()
    const handleChange = (e) => {
       setSelectedValue(e.target.value)
    }

    return (<div>
       <br />
            <input type='radio' name='delivery_stat' id='delivery' value='Pending delivery' onChange={handleChange}/>
            <label htmlFor="pending" for='Pending delivery'>Pending delivery</label>
            <br />
            <input type='radio' name='delivery_stat' id='delivery' value='Complete delivery' onChange={handleChange}/>
            <label htmlFor="done" for='Complete delivery'>Complete delivery</label>
            
            <div>
              {selectedValue}
            </div>
    </div>)
}

ReactDOM.render(
  <App/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

CodePudding user response:

You'll need to manually control the <input> element's value and onChange props.

First, create the state for the value using useState for a functional component or this.setState for a class component, or using a global state management library (generally overkill for a simple form).

Then, pass the state value along with a setter function to the element.

More info in the docs here, although it unfortunately still uses class components, it's good practice to figure out how class components are written functionally using hooks anyway.

  • Related