Z
Z
Zhanna_K2020-10-06 21:49:40
React
Zhanna_K, 2020-10-06 21:49:40

How to hide a component in React when clicking outside the component?

Found only options using life cycle methods.

I use not class, but functional components. How to do it with hooks?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
8
8XL, 2020-10-07
@Zhanna_K

React.useEffect(()=>{
  document.addEventListener('onmousedown', handleClick)
    return()=> document.removeEventListener('onmousedown', handleClick)
}, [])

Explanation:
React.useEffect(()=>{
//вешаем листенер
  document.addEventListener('onmousedown', handleClick) 
// в зависимости хука заносим пустой массив. Таким образом мы с помощью хука выполним метод
 //componentDidMount(), вызвав useEffect 1 раз
}, [])

React.useEffect(()=>{
...какой-то код...
//удаляем листенер
 return ()=> document.removeEventListener('onmousedown', handleClick)
//после return прописываем методы, которые нужно выполнить после при размонтировании компонента
//componentWillUnmount() аналог на хуках
}, [])

about useRef is very accessible and conveniently written in the documentation. The principle is the same as in your example, only accessing properties is slightly different (refName.current...)

M
Mike, 2020-10-06
@insidermike

You can set the state of the component and change the state on click. In render, show or hide the child component depending on the state.

export const Foo = () = {
const [toggle, setToggle] = useState(false);

render (
<div onClick={() => setToggle(!toggle)}>Скрыть компонент</div>
{toggle ?  null : <Baz />}
)
}

V
Vladimir, 2020-10-06
@Casufi

On hooks, the life cycle is quite implemented https://reactjs.org/docs/hooks-reference.html#useeffect
I just can’t think of what the life cycle and click outside the component have to do with it.

V
Vetal1992, 2021-11-16
@Vetal1992

Perhaps the simplest option, without unnecessary imports, which will work everywhere:

const SomeComponent = () => {
    const shovHide = () => {
        let a = document.getElementById('text')
        if (a.style.display === 'none') {
            a.style.display = 'block'
        } else if (a.style.display === 'block') {
            a.style.display = 'none'
        }
    }

    return (
        <div>
            <button onClick={shovHide}>
                push to shov\hide
            </button>
            <a id='text' style={{ display: 'none', fontSize: '1vw' }} href="">some text some text</a>
        </div>
    )
}

export default SomeComponent;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question