'I want to choose one specific option when clicked on button and button should got disabled in react
I have a 2 components in parent component I called child component, and in child I've 3 radio options and a button, what i want is, when i click on button, one specific option should select and button got disabled , but if i choose any other options then button got clickable again and that information i've to send back to parent component.
Now what is happening is click on button state is not updated for the first time. Means When i click the button it select the specific option and button got disabled but immediately it changes.
// parentComponent.js
<ChildComponent optionValue="positive"/>
// ChildComponent.js
<Button disabled={sentimentButtonValue} onclick={approveSentiment(e,optionValue)}> Approved </Button>
<RadioGroup row name="row-radio-buttons-group">
{['Negative', 'Positive', 'Neutral'].map((item) => (
<FormControlLabel
value={item}
checked={checkedValue.toLowerCase() === item.toLowerCase()}
control={<Radio />}
label={item}
onChange={changeSuggestedValue}
/>
))}
// logical code:
const [checkedValue, setCheckedValue] = useState('');
const [sentimentButtonValue, setSentimentButtonValue] = useState(false);
const {optionValue} = props;
const approveSentiment = (e, optionValue) => {
setCheckedValue(optionValue);
setSentimentButtonValue(true);
console.log(sentimentButtonValue); // it should update the state and button got disabled
}
const changeSuggestedValue = (e) => {
setCheckValue(e.target.value);
setSentimentButtonValue(false);
}
Solution 1:[1]
useEffect(()=>{
setSentimentButtonValue(true);
},[checkedValue]);
Use useEffect hook to immediately get the updated state value of 'checkedValue' and to set the value for setSentimentButtonValue to 'true'.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Subhash Beniwal |
