0

New to ReactJS.

I'm attempting to build a little component that moves some components around a container. The idea is that the user clicks on a button and the divs position changes.

I've tried to use Object.keys and Object.entries neither of them worked. I tried to create an array out of this.state so that I could just do array.map() but it did not work.

constructor(props) {
    super(props);
    this.handleShuffle = this.handleShuffle.bind(this);

    this.state = {
        redLeft: 0,
        redTop: 0,
        blueLeft: 0,
        blueTop: 70
    }
}

getRandomNumber (min, max) {
    return min + (Math.floor(Math.random() * (max-min)))
}

handleShuffle() {
    const min = 0;
    const max = 230;

this.setState({
    redLeft: this.getRandomNumber(min, max),
    redTop: this.getRandomNumber(min, max),
    blueLeft: this.getRandomNumber(min, max),
    blueTop: this.getRandomNumber(min, max),
});
}

The code above is as far as I got, it works but surely there is a way to loop over the different properties in this.state and call the function for each item?

Rue
  • 49
  • 1
  • 10
  • Possible duplicate of [Iterate through object properties](https://stackoverflow.com/questions/8312459/iterate-through-object-properties) – Heretic Monkey Jan 27 '19 at 21:14

2 Answers2

0

You could use reduce if your state only ever includes keys you want to apply the random number to:

this.setState((prevState) => (Object
  .keys({...prevState})
  .reduce((newState, next) => {
    newState[next] = this.getRandomNumber(min, max);
    return newState;
}, {})));
A Macdonald
  • 814
  • 1
  • 7
  • 10
-1

Not sure why Object.keys doesn't work for you but it does actually work. Here, I loop over the keys of this.state and set the state for that key.

class Foo extends React.Component {
     constructor(props) {
        super(props);
        
        this.state = {
            redLeft: 0,
            redTop: 0,
            blueLeft: 0,
            blueTop: 70
        }
    }
    
    componentDidMount () {
       this.handleShuffle()
    }
  
    getRandomNumber (min, max) {
        return min + (Math.floor(Math.random() * (max-min)))
    }
  
    handleShuffle() {
        const min = 0;
        const max = 230;
        
        Object.keys(this.state).map(k => {
           this.setState({ 
             [k]: this.getRandomNumber(min, max)
           })
        })
    }
    
    render () {
      return JSON.stringify(this.state)
    }
}

ReactDOM.render(<Foo />, document.getElementById('foo'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="foo"></div>
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81