Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

78
Visualizações
create multiple react checkboxes from JS object

I have an Object in state which stores the current value of four 'Risk Type' checkboxes

riskTypes: {"Fraud": true, "Steal": true, "Scam": true, "Theft": true},

on the subcomponent to render them I use:

Object.keys(this.props.riskTypes).forEach(key => {
          <li>
            <label>
              <input
                type="checkbox"
                value={key}  
                checked={this.props.riskTypes[key].value}
                onChange={this.handleRiskTypeChange}
              /> {key}
            </label>
          </li>
        })
      }

but this doesn't work, nothing is rendered, however if i console.log them instead of create checkboxes, it prints them fine. Any help much appreicated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

React expects JSX in some form, whether it's some HTML, or an array of HTML. forEach doesn't deliver that as it mutates the array rather than returning a new array.

map over the Object.entries to produce some JSX based on the information in state, and when you come to update the new state make sure that you keep the retain the old state properties.

I'm also using a name attribute on the input elements.

const { Component } = React;

class Example extends Component {

  constructor(props) {
    super();
    this.state = {
      riskTypes: props.riskTypes,
      tempProp: 'temp',
      tempProp2: 'temp2'
    };
  }

  handleRiskTypeChange = (e) => {

    // Get the name of the input, and its checked value
    const { name, checked }  = e.target;

    // Because state is a nested object we
    // 1) need to keep the state
    // 2) update `riskTypes` using the existing
    // riskTypes values, and updating only the one we
    // need to update based on the name of the input
    this.setState({
      ...this.state,
      riskTypes: {
        ...this.state.riskTypes,
        [name]: checked
      }
    }, () => console.log(JSON.stringify(this.state)));
  }

  getRiskTypes = () => {
    const { riskTypes } = this.state;
    const entries = Object.entries(riskTypes);
    return entries.map(([key, value]) => {
      return (
        <li>
          <label>
            <input
              name={key}
              type="checkbox"
              value={key}
              checked={value}
              onChange={this.handleRiskTypeChange}
            />{key}
          </label>
        </li>
      );
    });
  }

  render() {
    return (
      <ul>{this.getRiskTypes()}</ul>
    );
  }

};

const riskTypes = {'Fraud': true, 'Steal': true, 'Scam': true, 'Theft': true };

ReactDOM.render(
  <Example riskTypes={riskTypes} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda