I'm very new to React and having some trouble with what I thought would be a simple ternary operator. I'm just trying to display a minus sign by default, and a plus sign when it's clicked. I wrote a ternary operator in my JSX and set the initial state of the component to a false, boolean, and switch it when clicked. Seems pretty simple.
The page displays a plus sign by default, though, and I'm not sure why. When I click on it, it doesn't change and the console.log I have in the code displays the boolean. Anyone have any idea what's up? Thanks in advance. Here's the code for my component:
import React, { Component } from 'react';
class Header extends Component {
constructor(props) {
super(props);
this.state = {
showMinus: false,
};
this.changeSign = () => {
this.state.showMinus = !this.state.showMinus;
console.log('CLICKED ', this.state.showMinus);
}
};
render() {
return (
<div className="header">
<div>State: {this.state.showMinus}</div>
<div>30%</div>
<div>$200000</div>
<div>85%</div>
<div>
{this.state.showMinus ? <span className="plusOrMinus" onClick={this.changeSign}> - </span>
:
<span className="plusOrMinus" onClick={this.changeSign}> + </span>}
</div>
</div>
);
}
}
export default Header;
showMinusis false so second span gets rendered with+as text. Your ternary is backwards if you want different default based onfalse