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: '',
}
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>