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

179
Visualizações
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 Respostas
Responde à pergunta

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 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