skip to Main Content
<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


  1. 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:

    import React, { useState, useEffect } from 'react';
    
    // Assuming you have a functional component
    const YourComponent = () => {
      // State to manage the radio button selection
      const [test, setTest] = useState({});
    
      // Simulating the effect of fetching data from the database
      useEffect(() => {
        // Replace this with your actual data fetching logic
        // For demonstration purposes, using a setTimeout to simulate an asynchronous operation
        const fetchDataFromDatabase = () => {
          setTimeout(() => {
            // Assuming this is the data you get from the database
            const dataFromDatabase = {
              c: true // or false, or undefined if there is no data
            };
            setTest(dataFromDatabase);
          }, 1000); // Simulating a delay
        };
    
        fetchDataFromDatabase();
      }, []); // Empty dependency array ensures the effect runs only once
    
      // Event handler for radio button change
      const handleRadioChange = (value) => {
        setTest({
          ...test,
          c: value
        });
      };
    
      return (
        <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={() => handleRadioChange(true)}
              />
              <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={() => handleRadioChange(false)}
              />
              <label className="form-check-label" htmlFor="testn">
                No
              </label>
            </div>
          </div>
        </div>
      );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
  2. You don’t have to use any conditioanl expression there like test?.c==true or false especially optional chaining(?.)

    Just leave it as it is and use defaultChecked attribute instead checked.

    defaultChecked is the uncontrolled equivalent, which sets whether the component is checked when it is first mounted

    <input type="checkbox" defaultChecked={test.c} />
    

    One more thing you don’t have to use ?. unless you want to get the inner property

    for example:

    let test = {
        c:true,
        inner:{
          c:false
        }
    }
    

    For a case, we can avoid undefined error while getting test.inner2?.c here inner2 is also an object but we don’t know about it’s existance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search