Discovering the Nature of Truth in React.JS

Merrin Macleod
2 min readAug 28, 2020

--

Today I wrote a simple tabbed show and hide feature in React.JS. There are components for previews, and then a component showing more details of the item that is active.

It starts off with nothing active, so the state is initially set as null.

const [activeItem, setActiveItem] = useState(null);const handleClick = (itemIndex) => {
setActiveItem(itemIndex);
};

A handleClick event is passed through to the preview components so that they can set themselves as the active item.

<ItemHeader
data={ item }
index={ index }
onClick={ handleClick }
active={ index === activeItem }
/>

When the preview is clicked, it sets itself as the active item, using the index and handler that have been passed in from the parent.

<div onClick={ () => props.onClick(props.index) }>

If one of the items is active, a FullItem component is rendered.

{
activeItem && (
<FullItem data={ props.items[activeItem] } />
)
}

I got this far and thought: great. I am a genius and a professional with many skills. But I had forgotten something.

You see, I more frequently program with Ruby, where I would always expect the index of an array to be truthy:

➜  ~ irb
irb(main):001:0> 0 && "a"
=> "a"
irb(main):002:0> nil && "a"
=> nil

But this is Javascript:

➜  ~ node
Welcome to Node.js v12.18.0.
Type ".help" for more information.
> 0 && "a"
0
> null && "a"
null

So it needs to be more specific.

{
(activeItem !== null) && (
<FullItem data={ props.items[activeItem] } />
)
}

What catches you out when switching between programming languages?

--

--