Understanding React Pure Components
I’ve been following this tutorial for Pure Components in React
at the equals signs it’s throwing a parsing error for Unexpected token. What I’ve looked up so far suggest that I might need to add a .babelrc
file, but he doesn’t get into that until Chapter 8 and I’m still in Chapter 2, so that seems off track. Creat-React-App does start with some basic eslint
. So maybe I should be looking at that instead?
Parsing error: Unexpected token:
https://github.com/TurtleWolf/ReactCookBookChapter_03
Numbers.js
// Dependencies
import React, { Component } from 'react';
// Components
import Result from './Result';
// Styles
import './Numbers.css';
class Numbers extends Component {
state = {
numbers: '', // Here we will save the input value
results: [] // In this state we will save the results of the sums
};
handleNumberChange = e => {
const { target: { value } } = e;
// Converting the string value to array
// "12345" => ["1", "2", "3", "4", "5"]
const numbers = Array.from(value);
// Summing all numbers from the array
// ["1", "2", "3", "4", "5"] => 15
const result = numbers.reduce((a, b) => Number(a) + Number(b), 0);
// Updating the local state
this.setState({
numbers: value,
results: [...this.state.results, result]
});
}
render() {
return (
<div className="Numbers">
<input
type="number"
value={this.state.numbers}
onChange={this.handleNumberChange}
/>
{/* Rendering the results array */}
<ul>
{this.state.results.map((result, i) => (
<Resultkey={i} result={result} />
))}
</ul>
</div>
)
}
}
export default Numbers;
import React, { Component } from 'react';
class Result extends Component {
render() {
return<li>{this.props.result}</li>;
}
}
export default Result;