• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

141
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 3 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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda