ApathyBear ApathyBear - 4 months ago 45
React JSX Question

Reactjs: Jsx ternary inline of a component (nested ternaries)

I have a react-bootstrap

<Checkbox >
.

It looks like this:

<Checkbox inline onClick={this.handleInclude}> Include </Checkbox>


On some occasions I want the Checkbox to be checked. The api suggests doing the following if you want it checked:

<Checkbox checked inline onClick={this.handleInclude}> Include </Checkbox>


So now I only want to use the
checked
keyword during certain states.. so I tried using a ternary statement:

<Checkbox
{this.state.chkbox === true ? "checked" : "" }
inline
onClick={this.handleInclude}>
Include
</Checkbox>


But this throws an
Unexpected token
error. How are you supposed to do this with react?

EDIT:

I neglected to mention that the checkbox is indeed wrapped in a ternary

{this.state.currentView == "timeline" ?
<Checkbox
{this.state.chkbox === true ? "checked" : "" }
inline
onClick={this.handleInclude}>
Include
</Checkbox>
: ""
}


I am getting a JSX token error while using the inner
{ }
tags in the ternary operator.

Answer

React handles boolean form inputs using the checked property.

<input type={"checkbox"} checked={true} />
<input type={"checkbox"} checked={false} />

The component should listen for onChange events, especially when it's a controlled form input.

<input type={"checkbox"} checked={this.state.checked} onChange={this.onChange} />

Also, heads up:

Be aware that, in an attempt to normalize change handling for checkbox and radio inputs, React uses a click event in place of a change event. For the most part this behaves as expected, except when calling preventDefault in a change handler. preventDefault stops the browser from visually updating the input, even if checked gets toggled. This can be worked around either by removing the call to preventDefault, or putting the toggle of checked in a setTimeout.

To summarize, do not call event.preventDefault() in your this.onChange(event) component method.


Edit

In JSX, the following syntax means the same thing.

<input checked />
<input checked={true} />

Please see the boolean attributes section in the docs.