0

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.

melly18
  • 87
  • 3
  • 11
  • 1
    Wait, so are you trying to *default to* `0` if `savedId` is null or 0? What are you trying to do here? – kelsny Nov 01 '22 at 19:25
  • 1
    Not Typescipt, Javascript sees that 0 as falsy. Be more explicit `saveId == null ? null : ` will render `null` if `saveId` = `undefined` OR `null` – Wainage Nov 01 '22 at 19:27
  • @caTS I don’t want it to default to 0, I’m trying to get savedId to match the index of the array of data I am trying to render in the Accordian component, so 0 being the first index of data I want isn’t rendering because it thinks 0 is falsy, but I want 0 included. – melly18 Nov 01 '22 at 19:48

1 Answers1

1

Instead of checking for it's truthiness, you could check if the savedId is a number or not.

{typeof saveId === 'number' && <Accordion />...}

0 is a falsy value, that's why your content does not render, because the condition is not fulfilled.

kind user
  • 40,029
  • 7
  • 67
  • 77