Pass a function to a child component

Viewed 64

When I pass a function that is executed with the click event it is executed twice.

I have checked and when clicking from the child I cannot do event.preventDefault () since it does not arrive as an argument.

How can I pass the function so that it only runs once?

Parent component
The function that I pass from the parent is handleClickSelectPrice

export const FilterForm = ({ display }) => {
  const { priceFilters } = useSelector(selectSearchFilters);
  const dispatch = useDispatch();

  const handleClickSelectPrice = (priceFilter) => {
    priceFilter.isActivated
      ? dispatch(desactivatePriceFilter({ priceFilter: priceFilter.textKey }))
      : dispatch(activatePriceFilter({ priceFilter: priceFilter.textKey }));
  };

  return (
    <>
      <div>
        <Input name='nombre' icon={<MdSearch />} />

        <Select
          options={priceFilters}
          defaultLabel='Ordenar por precio'
          fullWidth
          setOptionSelected={handleClickSelectPrice}
        />
      </div>
    </>
  );
};

Child component
I have checked and option argument to handleClickOption arrives fine

export const Select = ({ options, defaultLabel, setOptionSelected }) => {
  const [label, setLabel] = useState(defaultLabel);
  const [showOptions, setShowOptions] = useState(false);

  const handleClickOption = (option) => {
    setShowOptions(false);
    setLabel(option.label);
    setOptionSelected(option);
  };

  return (
    <>
      <div className='selected-container'>
        <div className='selected' onClick={() => setShowOptions(!showOptions)}>
          <p>{label}</p>
          <GoChevronDown />
        </div>
        <div className='select-box'>
          <div className={`options-container ${showOptions ? 'active' : ''}`}>
            {options.map((option) => (
              <SelectOption option={option} onClick={handleClickOption} />
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

1 Answers

Please check your index.js, you may need to remove strict mode from there...

  ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Try by changing it to

 ReactDOM.render(
        <App />,
      document.getElementById('root')
    );
Related