简体   繁体   中英

React - How to set className conditionally from a json file

I have the following piece of code for my component. The desired behaviour for the button is to change the className for each li, but this is not working.

const Booking = (props) => {
let { hidden } = useContext(ContextBooking)
let completed = props.completed

    return (
            <li 
                className={ //should change according to the button click below
                   completed && hidden ?
                      'booking-complete hide'
                   : completed ?
                      'booking-complete'
                   : 
                      'bookings'
      }}
                key={props.id}
                id={props.id}
            >
                <h3>{props.date}</h3>
                <h4>{props.time}</h4>
                <h5>{props.name}</h5>
            </li>

    )
}

{!completed && (
        <button 
          onClick={() => {
            if (!completed && !hidden) {
              completed = !completed //does make it false
              hidden = !hidden //does make it false
            } //above works, but won't change classname for each 'li'
            else if (completed && hidden) {
              completed = !completed
              hidden = !hidden
            }
          }}>
          Complete
        </button>
      )}

In another component, I am creating multiple of these 'Booking' components, by filling in the details with info that come from a json file

const DisplayBookings = () => {

    const display = (day) => allBookings.map(item => //allBookings is a json file
        item.day === day &&

        <Booking
            completed={item.completed}
            key={item.id}
            id={item.id}
            time={item.time}
            name={item.name}
            date={item.date} 
        />
    )

I emphasised json file as I believe it could be the source of the problem?

A component can in most cases not update its own props, and doing so even if possible is an antipattern. You can instead use state for updating the components state.

You can create hooks for setting state like this:

const [isCompleted, setIsCompleted] = useState(props.completed);
const [isHidden, setIsHidden] = useState(hidden);

Then in your onClick you use this to update the values:

setIsCompleted(!isCompleted);
setIsHidden(!isHidden);

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