Hello,
I am trying to build a JS calculator using React and I have ran into a blocker.
Here is my code so far.
HTML
<div id="root"></div>
JS
// Components
class App extends Component {
render() {
return (
<div className="App">
<Title/>
<Calculator/>
</div>
);
}
}
class Title extends Component {
constructor(props) {
super(props);
this.content = 'ReactJS Calculator';
}
render() {
return (
<div className='Title'>
<h1>{this.content}</h1>
</div>
);
}
}
// Pseudocode:
// Store state here for buttons panel and display panel and update whenever the user clicks a button
class Calculator extends Component {
render() {
return (
<div className="Calculator">
<DisplayPanel />
<ButtonPanel />
</div>
);
}
}
class DisplayPanel extends Component {
constructor() {
super();
// Define the initial state:
this.state = { display: 0 };
}
render() {
return (
<div className="DisplayPanel">
{ this.state.display }
</div>
);
}
}
class ButtonPanel extends Component {
constructor(props) {
super(props);
this.buttonsArr = ['CE', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'x', '-', '/', '+', '='];
}
render() {
return (
<div className="ButtonPanel">
{
this.buttonsArr.map((value, index) => <Button
key={index}
value={value}/>)
}
</div>
);
}
}
class Button extends Component {
constructor(props) {
super(props);
this.state = { ...props };
}
handleClick(e) {
console.log(e.target.innerHTML);
}
render() {
return (
<div className={`Button button${this.props.value}`}
onClick={this.handleClick}>
{ this.props.value }
</div>
);
}
}
// Rendering
ReactDOM.render(<App />, document.getElementById('root'));
CSS
.DisplayPanel {
width: 45%;
height: 145px;
margin: auto;
border: 2px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.Title {
text-align: center;
}
.ButtonPanel {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
width: 45%;
padding: 10px 0;
margin: auto;
border: 2px solid black;
justify-items: center;
}
.Button {
display: flex;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
border-radius: 5px;
border: 2px solid black;
padding: 5px;
cursor: pointer;
box-shadow: 1px 2px rgba(0,0,0,0.5);
}
.Button:hover {
box-shadow: none;
transition: box-shadow 0.3s;
}
The Question
I do not know how to get the button component to communicate with the displayPanel component. I know that when the user clicks a button it should somehow change the state of the displayPanel component but I’m not sure how this is usually achieved?
Apologies if it is a basic question. I am very new to react. Any help is appreciated!