user12302978
user12302978

Reputation:

I need to set the checkbox to enabled when its value is true

I need to set like if the value of check box is coming true then check box show selected if the value comes false check box gets selected but what happening its value getting true from the backend I am storing value in the state rules but it's not getting enable and if the value is getting true also I am not able to check and unchecked checkbox when value is true checkbox not check when value it's true why it's happening not sure also I am trying to set onChange but getting confused how to set onchange

value coming from backend

NameMatch: true
Match: true

SearchForm component

export default function SearchForm() {

const { setRules, rules, fetchSearch } = useRule();
const [changeRuleSettings, setChangeRuleSettings] = React.useState(false);
React.useEffect(() => {
    fetchSearchRule();
  }, []);

const handleCheckBoxChange = (e) => {
    setRules((prevRules) => ({
      ...prevRules,
      [e.target.name]: !prevState[e.target.checked],
    }));
  };

 return (
 <Grid item xs={4}>
          <Box className={classes.formText}>
            <Checkbox
              style={style}
              name="NameMatch"
              checked={rules.NameMatch}
              color="primary"
              onChange={handleCheckBoxChange}
            />
            <Typography variant="subtitle2" noWrap={true}>
              Match
            </Typography>
          </Box>
        </Grid>
        
)
}

Upvotes: 1

Views: 127

Answers (1)

XdertY
XdertY

Reputation: 21

If I am understanding the question correctly, you are asking what should the onChange function exactly do. So basically you need to switch the values of the property, that the Checkbox is dependent on. For example, if the backend returns :

exactNameMatch: true
partialNameMatch: true

Then for the first checkbox, when it is clicked, the value of exactNameMatch should be set to false. An example implementation would look something like this:

onChange={(e) => setRules((prevRules) => ({...prevRules, exactNameMatch: !prevRules.exactNameMatch}))}

For the second checkbox the onChange will be identical, with the small difference, that instead of exactNameMatch you would use partialNameMatch.

Another possibility is to implement the handleCheckBoxChange function like so:

  const handleCheckBoxChange = (e) => {
          setRules((prevRules) => ({...prevRules, [e.target.name]: !prevRules[e.target.name]}))
}

Where e.target.name is respectively exactNameMatch or partialNameMatch, based on the values you have passed to the name properties of the Checkbox component. Hope I managed to understand your problem correctly and actually help you!

Upvotes: 1

Related Questions