5

I am trying to use defaultChecked in reactjs when using map function to only one radio button. But How can I acomplish it?

{colors.map((color, index) => {
      return (
        <label className="color-checkmark" key={index}>
          <input
            type="radio"
            checked="checked"
            name="color"
            value={color}
            // defaultChecked
          />
        </label>
      );
    })}

If I use defaultChecked there it will be set to every radio button.

2
  • which item do you want checked by default? Commented May 19, 2019 at 20:14
  • First item to be checked by default. Commented May 19, 2019 at 20:14

3 Answers 3

4

You need to remove the checked="checked" attribute as it conflicts with the defaultChecked attribute. And then add defaultChecked={index === 0}

Sign up to request clarification or add additional context in comments.

Comments

3

If you want the first item checked

{colors.map((color, index) => {
  return (
    <label className="color-checkmark" key={index}>
      <input
        type="radio"
        name="color"
        value={color}
        defaultChecked={!(!!index)}
      />
    </label>
  );
})}

what does !! do?

the !! ensures that the value will always be a boolean or converted to a boolean.

5 Comments

This didn't work. It just checked every radio button.
using the index?
yes using index also it just set every radio button as checked in HTML DOM.
see the code above and remove checked="checked" from the input.
you don't actually need to do !(!!index) in this case, since it's a zero index, you can do !index and it will evaluate to true.
2

You need to add a condition to your defaultChecked, and remove the checked property:

const colors = ['blue', 'green', 'red']

function App() {
  return colors.map((color, index) => (
    <label key={index}>
      <input
        type="radio"
        name="color"
        value={color}
        defaultChecked={index === 0}
      />
      <span style={{color}}>{color}</span>
    </label>
  ))
}

ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app">euoeu</div>

3 Comments

I just want my first radio button to be checked by default without any criteria.
I updated my answer then. You need to set defaultChecked only if index === 0. Don't forget to remove the checked property you put in your example.
It does for me, see the example. It means you forgot something, check again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.