1

I want to pass props to my react component and have a function where I toggle the font weight of a span between bold and normal.

My React component:

ReactDOM.render(
  <div>
    <FontChooser min='4' max='40' size='16' text='Fun with React!' bold='false'/>
   </div>,
document.getElementById('container'))
;

And I am trying to pass the bold = 'false' prop to the initial state of the component like this:

class FontChooser extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
        hidden: true,
        bold: this.props.bold,
        size: 16 
    }
    }

And then I have the function

toggleBold() {
        this.setState ({
            bold: !this.state.bold
        });
    }

And it should render:

render() {
        var weight = this.state.bold ? 'bold':'normal';

    return(
           <div>
           <input type="checkbox" id="boldCheckbox" onChange={this.toggleBold.bind(this)}
           <span id="textSpan" style ={{fontWeight: weight, fontSize: this.state.size }}>. 
                 {this.props.text}</span>
           </div>

My problem is that this.props.bold should return false but the ternary operator executes 'bold' which should only be executed if this.props.bold is true. It seems like it is treating this.props.bold as a truthy value rather than falsy, even though it is set to false in the component property.

So does this.props always return a truthy value when we pass it to component sate? Even if it is set to 'false' in the component prop definition?

JC.
  • 17
  • 2
  • 2
    You're passing `false` as a string rather than as an actual false value, your JSX should look like `` Since 'false' is a non-empty string, it is truthy. – Rodentman87 Jun 21 '20 at 23:48
  • Does this answer your question? [How are boolean props used in React?](https://stackoverflow.com/questions/60816731/how-are-boolean-props-used-in-react) – user120242 Jun 22 '20 at 01:01

1 Answers1

0

You are passing the bold prop as a string and since the value passed is not an empty string, the this.state.bold is being evaluated as true in the ternary.

<FontChooser min='4' max='40' size='16' text='Fun with React!' bold='false'/>
                                                                    ^

let bold = 'false'

console.log(!!bold)

Solution, Pass value for bold as a boolean instead.

<FontChooser min='4' max='40' size='16' text='Fun with React!' bold={false}/>
subashMahapatra
  • 6,339
  • 1
  • 20
  • 26