Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!