2

I have the following component:

import React, { Component } from 'react';

import Action from './action.jsx';
import SingleGridEl from './singleGridEl.jsx';

class Grid extends Component {

    constructor(props) {
        super(props);
        this.maxN = 110;
        this.tempArray = [];
        this.question;

        this.state = {
            n1: false,
            n2: false,
            n3: false,
            n4: false,
            n5: false,
            n6: false
        }

        this.hideSingleGrid = this.hideSingleGrid.bind(this);
    }

    getRandomN() {
        var randomN = Math.floor((Math.random() * this.maxN) + 1);

        if(this.tempArray.indexOf(randomN) === -1) {
            this.tempArray.push(randomN);
        }
        else {
            randomN = this.getRandomN();
        }

        return randomN;
    }

    getRandomQuestion() {   
        this.question = this.props.current.data.questions[this.getRandomN()];
        return this.question;
    }

    hideSingleGrid(el, val) {
        this.setState({
            el: val
        })

        console.log('sdfsdf');
    }

    render() {
        this.getRandomQuestion();

        return (
            <section className="game">
                <div className="grid">

                    <div className="row">
                        <SingleGridEl visibility={this.state.n1} />
                        <SingleGridEl visibility={this.state.n2} />
                        <SingleGridEl visibility={this.state.n3} />
                        <SingleGridEl visibility={this.state.n4} />
                        <SingleGridEl visibility={this.state.n5} />
                        <SingleGridEl visibility={this.state.n6} />
                    </div>
                </div>

                <Action t={this.hideSingleGrid} question={this.question} getRandomQuestion={this.getRandomQuestion.bind(this)}/>
            </section>
        );
    }
}

export default Grid;

Is it possible to choose what state property needs updating together with its value?

I have tried this:

hideSingleGrid(el, val) {
    this.setState({
        el: val
    })
}

so that it could be used like:

this.hideSingleGrid(n2, true);
this.hideSingleGrid(n1, true);

but it doesn't work (state doesn't get updated)..

Aessandro
  • 5,517
  • 21
  • 66
  • 139

1 Answers1

1

You can do it two ways:

var s = {};
s[el] = val;
this.setState(s);

or a bit fancier:

this.setState({[el]: val})

Assuming el is a name of the property to update.

Amid
  • 21,508
  • 5
  • 57
  • 54