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

172
Vistas
How do I make the random array choice the value of my state?

I'm trying to randomly select items from my 'items' array, how do I make the randomly selected item the value of the 'randomItem' state? Heres what I have so far.

var items = ['joe', 'joe', 'mama', 'one direction went the other direction'];

this.state.randomItem items[Math.floor(Math.random()*items.length)]





export default class App extends Component {

state = {
      randomItem: '',
    }    
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Pass in the random item to the component, and then set the state with it.

const { Component } = React;

class Example extends Component {

  constructor(props) {
    super();
    this.state = { item: props.item };
  }

  render() {
    const { item } = this.state;
    return (
      <div>{item}</div>
    );
  }

};

const items = ['joe', 'joe', 'mama', 'one direction went the other direction'];

const randomItem =  items[Math.floor(Math.random() * items.length)]


ReactDOM.render(
  <Example item={randomItem} />,
  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