'Apply onClick functions based on conditions within components React

I have a component which renders a bunch of components called ActionItem

            <ActionItem title={'Client Assigned'} icon={<MdOutlineAssignmentTurnedIn />} />
            <ActionItem title={'Inital Client Follow Up'} icon={<BsFillPersonCheckFill />} />
            <ActionItem title={'Validated Need'} icon={<BiDonateHeart />} />

            <ActionItem title={'Initiated Discovery'} icon={<RiCompassDiscoverLine />} />
            <ActionItem title={'Service In Progress'} icon={<GiProgression />} />
            <ActionItem title={'Fulfilled The Need'} icon={<ImCheckmark />} />

Inside of my ActionItem I have a function: handleToggle() which fires onClick and pretty much adds or removes an "active" class. I want this function available to every component EXCEPT the one with the title of 'Client Assigned'

ActionItem component:

  const [toggleItem, setToggleItem] = useState(false)
  const [date, setDate] = useState('')

  const handleToggle = () => {

    setToggleItem(!toggleItem)
    setDate(new Date())
    if (date !== '') {
      setDate('')
    }

  }

  useEffect(() => {
    title === 'Client Assigned' ? handleToggle() : null
  }, [])

  return (
    <React.Fragment>
      <div className={toggleItem ? 'ReportsModal' : 'ReportsModal not-active'}>
        <span
          style={title === 'Fulfilled The Need' ? (
            { borderColor: 'green', backgroundColor: 'green', color: '#fff' }
          ) : null}
          className={'hover'}
          onClick={title === 'Client Assigned' ? handleToggle : null}>
          {icon}
        </span>
        <div>
          <h3>{title}</h3>
          <p>{date !== '' ? moment(date).format('D MMM YYYY') : date}</p>
          {toggleItem ? (
            <h5 onClick={handleInitComment} className='hover'><AiOutlinePlusCircle style={iconStyles} /> Add Comment</h5>
          ) : null}

        </div>
      </div>

the conditional I am trying to use is currently not working. Any advice?



Solution 1:[1]

You can create an array of banned/prohibited titles and use an AND operator in the onClick prop. For example:

function Component({ title, handleToggle }) {
  const bannedTitles = ["Client Assigned"];

  useEffect(() => {
    title === "Client Assigned" ? handleToggle() : null;
  }, []);

  return (
    <>
      <div
        onClick={() => !bannedTitles.includes(title) && handleToggleItem()}
      />
    </>
  );
}

export default Component;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Uriel Libano