How can I show checkbox checked in edit page if I get value of checkbox field = 1

This is my code for checkbox in ReactJs

              checked={ this.state.checked } 
              onChange={ this.handleCheckChange }

I am getting yes = 1 from database ,and I want to show checkbox checked else unchecked
How can I fix it?


Normally setting an input element’s checked property to a Boolean value held in state should work as expected.

  checked={ this.state.checked }
  onChange={ () => console.log("Changed") }


I don’t really get this. Can you make a small runable example on CodeSandbox to demonstrate your problem. You can hardcode the value from the database lookup.

So, combining the two: How in React to take a database result of 1, and perform an if on it at pageload to determine whether the box should be checked at load time.

Well pretty much like I demonstrated — that’s my point, it should work as is.

In my previous demo, I was hardcoding the checked value, but you could just as easily fetch this from a database and pop it into state. It shouldn’t make much difference to the result.

Here’s a second demo showing that.

The data is typically fetched in the componentDidMount lifecycle method, then stored in state, so that React can access that value when it comes to render the component.

If checked is returning as “yes” from the database, you could convert it like so:

const res = await api.getData();
const checked = res.checked === 'yes' ? true : false;
this.setState({ checked });

But storing a Boolean value as “yes” is a bad idea.

1 Like

I suppose the issue is that @xcfx2888 isn’t using an input element directly, but a (presumably) formik wrapper component. In this case the renderCheckBoxField() function (which should actually be a component BTW) probably just fails to forward the checked prop to the rendered checkbox… if that’s not it we’d have to see the implementation though.

Ok, cool. Out of interest, how can you tell that (I’ve never used Formik)?

It was just a guess based on the API really…

But yes, @xcfx2888 please clarify which library you’re using for form handling (if any).

1 Like

I know nothing of Formik… that being said.

So, api returns yes = 1, I’ll assume no = 0, psedu code time:

amIChecked: false

cdm() {
const ohai = await api.getData();
amIChecked: ohai.checked === 1 ? true : false;

{amIChecked ? ‘checked’ : null}


I may be off on the input ternary but that’s close (and Its late, lol). For MULTIPLE you would have to come up with a better way but, as I’m fond of saying, that’s out of scope :stuck_out_tongue:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.