<div className="form-group row mb-3">
<div className="col-sm-2" style={{ fontSize: '1rem' }}>
Test:{' '}
</div>
<div className="col-sm-4">
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
name="testy"
id="testy"
value="y"
disabled={test?.a === 'V' || test?.b != null}
checked={test?.c === true}
onChange={e => setTest(e.target.checked)}
/>
<label className="form-check-label" htmlFor="testy">
Yes
</label>
</div>
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
name="testn"
id="testn"
value="n"
disabled={test?.a === 'V' || test?.b != null}
checked={test?.c === false}
onChange={e => setTest(e.target.checked)}
/>
<label className="form-check-label" htmlFor="testn">
No
</label>
</div>
</div>
I have incoming data from a database that returns me a boolean and to reflect that in my radio button, I assigned it to checked
. So if test?.c
from the database is true, it will pick the yes radio button to be selected and if the value is false, it will pick the no radio button to be selected. This part is what I wanted and it is working.
But if i dont have a boolean returned from database, i would like to allow user to select which radio button to be clicked. But at the moment I cannot click any radio button currently. I found out the issue is because I am using checked
. But without using this checked
, i cant display the existing selection that is stored in database. Is anyone here familiar with radio buttons that can guide me on what I can do to fix this.
Basically what I want to do is to be able to display the result that is returned from the database test?.c
, if there is no data from test?.c
, I want to allow user to select the radio button to send the selected radio button to database to store in test?.c
so if user display this page, it will extract the test?.c
from db and display it
2
Answers
To achieve the functionality you’re looking for, you can modify your code to handle both scenarios. If test?.c is present, set the checked property based on its value. If it is not present, allow the user to interact with the radio buttons and store the selected value in the test?.c property. Here’s an updated version of your code:
You don’t have to use any conditioanl expression there like
test?.c==true
orfalse
especially optional chaining(?.)Just leave it as it is and use
defaultChecked
attribute insteadchecked
.defaultChecked
is the uncontrolled equivalent, which sets whether the component is checked when it is first mountedOne more thing you don’t have to use
?.
unless you want to get the inner propertyfor example:
For a case, we can avoid
undefined
error while gettingtest.inner2?.c
here inner2 is also an object but we don’t know about it’s existance.