1
1
12332112021-06-11 16:55:54
React
1233211, 2021-06-11 16:55:54

How to write such a switcher in react?

How to write such a switcher in react?
https://codepen.io/asistapl/pen/JKmkwJ

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-11
@1233211

function Switch({ options, value, onChange }) {
  const highlight = useRef();

  useEffect(() => {
    const activeButton = highlight.current.closest('.c-switch').querySelector('.is-active');
    highlight.current.style.width = `${activeButton?.offsetWidth ?? 0}px`;
    highlight.current.style.transform = `translateX(${activeButton?.offsetLeft ?? 0}px)`;
  }, [ value ]);

  return (
    <div className="c-switch">
      <div className="c-switch__highlight" ref={highlight}></div>
      {options.map(n => (
        <button
          key={n.value}
          className={n.value === value ? 'is-active' : ''}
          onClick={() => onChange(n.value)}
        >{n.text}</button>
      ))}
    </div>
  );
}

https://jsfiddle.net/4hbkm9e8/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question