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)
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
It’s a neat solution indeed!
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.
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)