Pass state property with onClick function

Hey,
I’m still a little stuck with the Pomodoro clock.
In my code I have the method called ‘substract’ which I want to make reusable by telling the method to use substract on whatever state prop gets inputted (this case sessionTime)

substract = (e) => {
       this.setState(prevState => ({
      e: prevState.e -1000
    }));
  };

Problem is I don’t know what I need to pass along with the onClick function:
<button onClick={() => this.substract(???)} >-</button>

I’ve tried this.this.state.sessionTime, sessionTime and 'sessionTime' but none of these seem to work.

Full code on codepen: https://codepen.io/MarijkeBroos/pen/BvwPYN?editors=0011

You should pass 'sessionTime' (a string) and change subtract to:

   substract = (e) => {
      this.setState(prevState => ({
      [e]: prevState[e] -1000
    }));
  };
1 Like

Worked, thanks!

I’ve never used [ ] like this before, only when addressing arrays. Is using [ ] this way React specific or just something I missed in Javascript? Sorry to ask, but I would love to know why it works :stuck_out_tongue:

Something you missed in JavaScript :wink:
Property accessors

I did miss that, thanks! XD

It’s a neat solution indeed! :+1:
But they are not Property Accessors, it existed even before the ES6. (I’m not sure when it came along, but it’s also available in C, C++ so I believe its there from the start)

Anyways, it is called Computed Proptery Names, came with ES6

You can find the examples and docs here:

Search for the word Computed property on the above page.

1 Like

I stand corrected :slight_smile:

Think I will browse more through the documentation from time to time, lot of useful info in there I’m not really familiar with. Also good to know that this method “Computed property” might not work in Internet Exporer or in a JSON environment.

It is a feature of Javascript (ES6). And you can’t use any sort of Javascript in JSON environment anyway.

Many of the ES6 features works in Internet Explorer, but you’d need babel to transpile your code, as you transpile JSX into JS with babel.

If you’re curious how this code looks in ES5 syntax, you can paste the following code into the online babel transpiler here: https://babeljs.io/repl/
(Just a quick mock of your current example)

// our state 
var state = {
	sessionTime: 8000,
    breakTime: 5000
};

// Just a mock of this.setState - ignore this for this example's sake
function setState(newState) {
	state = Object.assign({}, state, newState);
    // We can use ... spread operator here instead of Object.assign, but it would
    // Add more clutter into the transpiled code 
};

// Our example function
function subtract(key) {
 setState({
 	[key]: state[key] - 1000,
 })
};

// That's how we would call our function
// subtract('breakTime'); 
// subtract('sessionTime');

(Use Prettify option in the left sidebar to make the transpiled code look readable)