I am trying to render a React component on click of another component.
The onClick I set a savedId to be the eventKey of the component to render the correct data related to that specific index the array.
onClick call
<ListGroup>
{data.map((item: any, i) => (
<ListGroup.Item key={i} action eventKey={i}
onClick={() => {setSavedId(i); console.log(i)}}>
{item.first_name} {item.last_name}
</ListGroup.Item>
))}
</ListGroup>
The issue here is that when my savedId is equal to 0, nothing renders but when it is > 0, the component with the correct data is rendered.
Ternary
<Tab.Pane eventKey={savedId}>
{savedId ? <Accordian data={data[savedId]} /> : null}
</Tab.Pane>
My first thought was that since 0 is a "falsy" value, the condition is taking that as false and returning "null" as specified, but I've tried using the !! operator and the && operator and no luck...
!
<Tab.Pane eventKey={savedId}>
{!!savedId ? <Accordian data={data[savedId]} /> : null}
</Tab.Pane>
&&
{savedId && <Accordian data={data[savedId]} />}
! AND &&
{!!savedId && <Accordian data={data[savedId]} />}
This was my hacky solution and it worked at first but once the page was refreshed the data came back undefined when the savedId was 0
{savedId ? <Accordian data={data[savedId]} /> : <Accordian data={data[0]} />}
Not really sure how to make this line defensive enough to deal with savedId being equal to 0. Not sure why Typescript is freaking out about it.
Thanks.
Instead of checking for it's truthiness, you could check if the
savedIdis a number or not.0is a falsy value, that's why your content does not render, because the condition is not fulfilled.