简体   繁体   中英

Toggle css in react component is not applied

I have the following component which map over an array and display a set of buttons which they render specific content:

export const Bookings = ({bookings}) => {
    const [selectedBooking, setSelectedBooking] = useState(false);
    const handleSelectedBooking = (id, destination) => {}
    const handleToggleButton = () => {
        setSelectedBooking(!selectedBooking)
    }
    
    return(
       <div>
        {
          bookings.map(booking => (
            <button
              className={selectedBooking ? 'selectedBooking' : 'notSelectedBooking'}
              onClick={() => {
                handleSelectedBooking(booking.id, booking.destination)
                handleToggleButton()
              }}
            >
              {booking.destination}
            </button>
          ))
        }
       </div>
    )
}

Where I have these styles already defined but somehow the styles are not applied, did I miss anything?

You have a typo in your ternary operator. It should be selectedBooking instead of selectedBoking.

Did you import styles file in the current file, where you write your component?

Moreover, I recommend you using modules to set styles in your component. How this works: you name your css file like this MyStyles.module.css (.module is obligatory) and then import in React component file these styles like import styles from './MyStyles.module.css' . Then you set styles in jsx code like this: className={selectedBoking? styles.selectedBooking: styles.notSelectedBooking} className={selectedBoking? styles.selectedBooking: styles.notSelectedBooking} .

This approach makes classnames unique across all the project even though they have the same names in different css files.

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