Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACT - defaultChecked don't render check attribute on second load

I got my component who won't check the radio when i go to the /view/:id for the second time. I started in my list component with react-router at the index of the site, i click on the view button of an element, the radio is checked, i return in my list and go to another or the same element and it's not checked anymore. When i inspect the component in the React developer tool, the radio has the defaultChecked=true property.

import React from 'react';
import { connect } from 'react-redux';

class LicenseRadios extends React.Component {
  buildRadios() {
    let { licenses, activeValue } = this.props;

    return licenses.map(license => {
      let checked = false;

      if(activeValue !== undefined && activeValue === license.id){
        checked = true;
      }

      return (
        <div key={license.id} className="col l2">
          <p>
            <input name="license" type="radio" id={'licenseRdo_' + license.id} value={license.id} defaultChecked={checked} />
            <label htmlFor={'licenseRdo_' + license.id}>{license.label}</label>
          </p>
        </div>
      );
    });
  }

  render() {
    return (
      <div className="row">
        {this.buildRadios()}
      </div>
    );
  }
}

export default LicenseRadios;

I tried to change the defaultChecked for the checked attribute, but it require an onChange event. I don't understand this problem. Can anybody help me please?

Thank you

like image 659
Mike Boutin Avatar asked Sep 26 '22 12:09

Mike Boutin


2 Answers

The defaultChecked prop is only used during initial render. If you need to update the value in a subsequent render, you will need to use an onChange function to handle value changes.

Check out controlled components in the docs to better understand the problem you're having.

like image 148
Eric Avatar answered Oct 08 '22 11:10

Eric


use "undefined" for initial value for defaultChecked and re-render by setting it to true or false

const Example = () => {

  [checked,setChecked] = useState(undefined);
  
  useEffect(()=>{
  
    // fetch data
    
    setChecked(true);
  
  });
  
  return (
    <input type="checkbox" defaultChecked={checked} onClick={(e)=> changeValue(e)}/>
  );

}
like image 21
MirMohammad Musavi Avatar answered Oct 08 '22 13:10

MirMohammad Musavi