Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

77
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda