C
C
Captain Cocoa2021-10-25 15:59:54
React
Captain Cocoa, 2021-10-25 15:59:54

How to add the required class to the parent from the Child component?

There is such markup

<div className="App">
      <h1 className={preloader.wrapper}>
        <Preloader />
        Hello CodeSandbox
      </h1>
      <h2 className={preloader.wrapper}>
        <Preloader />
        Start editing to see some magic happen!
      </h2>
    </div>


The full code is https://codesandbox.io/embed/jolly-alex-14fs5?font...

For the component to work correctly, I need to manually add the preloader.wrapper class to each parent block, which is not very convenient.

Can you please tell me how to add the preloader.wrapper class to each parent automatically ?

On pure, native JS, I would do something like this https://jsfiddle.net/4nyg8kam/ but I don’t know how to implement it correctly in React.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-10-25
@RadCor

This is not accepted, and you do not need to.
Since all of these elements must have the same class, they must be the root elements of the Preloader component instances. The tag can be passed via props, just like the elements that are now adjacent:

function Preloader({ Tag = 'h1', children }) {
  return (
    <Tag className={s.wrapper}>
      <div className={s.preloader}></div>
      {children}
    </Tag>
  );
}

<div className="App">
  <Preloader>hello, world!!</Preloader>
  <Preloader Tag="h2">fuck the world</Preloader>
</div>

A
Aetae, 2021-10-25
@Aetae

Do it right like this:

<div className="App">
  <Preloader>
    <h1>
      Hello CodeSandbox
    </h1>
  </Preloader>
  <Preloader>
    <h2>
      Start editing to see some magic happen!
    </h2>
  </Preloader>
</div>

A crutch fraught with glitches:
useLayoutEffect(() => {
  const parent = ref.current.parentNode; // ref - корневой элемент
  parent.classList.add(preloader.wrapper);
  return () => {
    parent.classList.remove(preloader.wrapper);
  }
}, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question