How does this work?
I want to declare a variable inside of a react component class and use it in several different areas in my app.
The attempt looks like this:
class ColorPick extends React.Component {
colorInput;
constructor(props) {
super(props);
this.state = {
color: "Let's pick a color"
};
}
// use this many times in my app
colorInput = document.getElementById("colorInput").value;
changeColor(event) {
this.setState({
color: "#" + event.target.value,
backgroundColor: "#" + event.target.value
});
if (colorInput === "") {
this.setState({
color: "Let's pick a color",
backgroundColor: "#fff"
});
}
}
}
What happens is I get this error:
Error in ./src/components/colorpicker.jsx Syntax error: Unexpected token (12:8)
10 | } 11 |
12 | var colorInput = document.getElementById('colorInput').value; | ^ 13 | 14 | changeColor(event) { 15 | this.setState({
@ ./src/index.js 29:19-54
I don't understand why this happens, and I can't find any documents that explain this clearly.
How to declare global variables in React JS
So I did:
global.js:
global.colorInput = colorInput;
colorpicker.js:
import React, { Component } from 'react';
import Global from './global'
class ColorPick extends React.Component {
constructor(props) {
super(props);
this.state = {
color: "Let's pick a color"
};
}
var colorInput = document.getElementById('colorInput').value;
changeColor(event) {
this.setState({
color: '#' + event.target.value,
backgroundColor: '#' + event.target.value
});
if (colorInput === '') {
this.setState({
color: "Let's pick a color",
backgroundColor: "#fff",
});
}
}
I still get the same error. Why?
How do I create a globally accessible variable in React JS
Doesn't quite answer my question in the context I'm looking for.
How can I declare a variable inside of a react class/component and reuse it? How does that work?