简体   繁体   中英

How do I conditionally render an object to display one section of code if the object is not empty and one section of code if the object has key: value

I am trying to render a section of code if the object UPCOMING has data, and a different section of code if the object doesn't have data. The issue I am running into is when the object is empty, the key/value pairs used later in the code are throwing an error.

import React, { useState } from 'react'
import BasicCard from 'pages/EventsPage/EventsCard/index'
import EventsHeroImage from 'assets/images/events-hero-image.jpg'
import EventsHeroImageMobile from 'assets/images/events-mobile-hero-image.jpeg'
import CountdownTimer from 'pages/EventsPage/CountdownTimer/CountdownTimer'
import PlaceholderUpcomingShowImageDesktop from 'assets/images/placeholder-upcomng-show-image.png'
import PlaceholderUpcomingShowImageMobile from 'assets/images/placeholder-upcomng-show-image.png'
import { Grid } from '@material-ui/core'
import useStyles from './styles'

const EVENTS = [
  {
    month: 'AUG',
    day: '09',
    title: 'SUMMER 2019 SHOWCASE',
    time: '7:30PM-9:00PM',
    location: 'The Irenic, San Diego, CA',
  },
  {
    month: 'APR',
    day: '17',
    title: 'SPRING 2019 SHOWCASE',
    time: '7:30PM-9:00PM',
    location: 'The Irenic, San Diego, CA',
  },
  {
    month: 'AUG',
    day: '09',
    title: 'FALL 2019 SHOWCASE',
    time: '7:30PM-9:00PM',
    location: 'The Irenic, San Diego, CA',
  },
  {
    month: 'APR',
    day: '17',
    title: 'WINTER 2019 SHOWCASE',
    time: '7:30PM-9:00PM',
    location: 'The Irenic, San Diego, CA',
  },
]
const UPCOMINGEVENT = {
  title: 'WINTER 2020 SHOWCASE',
  date: 'JAN 24TH',
  location: 'THE IRENIC, SAN DIEGO',
  about:
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Consectetur cursus nunc faucibus justo enim, eget dignissimlacus turpis. Tincidunt sed mauris in volutpat. Sapien fringilla libero, facilisis elementum nisi lobortis amet porttitor. Velit risus diam sit feugiat velit enim et, euismodquis.',
}

const EventsPage = () => {
  const classes = useStyles()
  const [events, setEvents] = useState(EVENTS)
  const { title, date, location, about } = UPCOMINGEVENT
  const startDate = '04/23/2021'
  const endDate = '05/04/2021'
  return (
    <div>
      {/*-------------Mobile View--------------------- */}
      <Grid
        container
        direction='column'
        justify='center'
        alignItems='center'
        spacing={0}
        className={classes.allContainerMobile}
      >
        <div className={classes.headingContainerMobile}>
          <div>
            <p className={classes.allEventsTitleMobile}>ALL EVENTS</p>
          </div>
          {!UPCOMINGEVENT ? (
            <div>
              <div className={classes.parentDivImageMobile}>
                <div className={classes.ImageDivMobile}>
                  <img
                    src={EventsHeroImageMobile}
                    className={classes.placeHolderImageMobile}
                  />
                </div>
              </div>
            </div>
          ) : (
            <div>
              <Grid item sm={12} className={classes.gridMobile}>
                <div className={classes.countdownContainerMobile}>
                  <div className={classes.countdownParentMobile}>
                    <CountdownTimer
                      countdown={startDate}
                      unixEndDate={endDate}
                    />
                  </div>
                </div>
              </Grid>
            </div>
          )}
          {!UPCOMINGEVENT ? (
            <div>
              <div>
                <p className={classes.upcomingShowMobile}>UPCOMING SHOW</p>
              </div>
              <div>
                <p className={classes.noUpcomingShowsMobile}>
                  NO UPCOMING SHOWS...FOR NOW.
                </p>
              </div>
            </div>
          ) : (
            <div>
              <div className={classes.flyerImageMobile}>
                <div className={classes.upcomingShowParentMobile}>
                  <img
                    src={PlaceholderUpcomingShowImageMobile}
                    className={classes.imageStyleMobile}
                  />
                </div>
              </div>
            </div>
          )}
        </div>
        {UPCOMINGEVENT ? (
          <div>
            <div className={classes.upcomingShowsMobile}>
              <div className={classes.titleContainerMobile}>
                <p className={classes.upcomingShowTitleMobile}>
                  {/* {UPCOMINGEVENT.title} */}
                  {title}
                </p>
                {/* <p className={classes.upcomingShowTitleMobile}>
                  WINTER 2020 SHOWCASE
                </p> */}
              </div>
              <div className={classes.dateLocationContainerMobile}>
                <p className={classes.upcomingShowDateLocationMobile}>
                  {/* {UPCOMINGEVENT.date} | {UPCOMINGEVENT.location} */}
                  {date} | {location}
                </p>
                {/* <p className={classes.upcomingShowDateLocationMobile}>
                  JAN 24TH | THE IRENIC, SAN DIEGO
                </p> */}
              </div>
              <div className={classes.aboutContainerMobile}>
                <p className={classes.aboutUpcomingShowMobile}>
                  {/* {UPCOMINGEVENT.about} */}
                  {about}
                </p>
                {/* <p className={classes.aboutUpcomingShowMobile}>
                  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                  Consectetur cursus nunc faucibus justo enim, eget
                  dignissimlacus turpis. Tincidunt sed mauris in volutpat.
                  Sapien fringilla libero, facilisis elementum nisi lobortis
                  amet porttitor. Velit risus diam sit feugiat velit enim et,
                  euismodquis.
                </p> */}
              </div>
              <div className={classes.upcomingShowButtonContainerMobile}>
                <button className={classes.upcomingShowButtonMobile}>
                  BUY TICKETS
                </button>
              </div>
            </div>
          </div>
        ) : null}
        {!UPCOMINGEVENT ? (
          <div>
            <h2 className={classes.pastShowsMobile}>PAST SHOWS</h2>
          </div>
        ) : (
          <div>
            <h2 className={classes.pastShowsUpcomingMobile}>PAST SHOWS</h2>
          </div>
        )}

        <div className={classes.eventsCardMobile}>
          {events.map(({ month, day, title, time, location }, i) => (
            <BasicCard
              key={`${title}-${i}`}
              month={month}
              day={day}
              title={title}
              time={time}
              location={location}
            />
          ))}
        </div>
      </Grid>

I am not sure what I am doing wrong. Any help on this would be greatly appreciated.

When the object is empty, does it get the value undefined or null? Or does it get the value length 0? I'm thinking you maybe should use "Object.keys(obj).length === 0" as a conditional.

U might have to use null in stead of !UPCOMINGDATE

console.log(!{} === false);   // true
console.log(!{item: "yes"} === false); // true
console.log({item: "yes"} !== null);  // true
console.log({} === null);   // false

so it might help using (UPCOMINGDATE.== NULL) then render.

From the dev: The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations. Link

short example

    import React from 'react'

export default function parent() {
    const [events, setEvents] = useState(null)
React.useEffect(() => {
    getSomeData(id, Callback => {
        // Set the data here
        setEvents(callback)
    })
},[])
    // It will not render the data until its set bc its null
    // You can also map the child 
    return (
        <div>
            {events !== null ? <Child events={events}/> : null}
        </div>
    )
}




export default function Child(props) {
    return (
        <div>
            <p>props.events.title</p>
            <p>props.events.date</p>
        </div>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM