mercredi 27 janvier 2021

React: Design pattern that uses a Ref to set style of the parent component

I would like to ask if this is a sensible component design pattern in React.

Let's say I have the following components, App, ContentContainer and WithBlueBackground. The idea is to use a Ref to set a blue background on the ContentContainer with the WithBlueBackground component.

The simplified code would look something like this.

// App.js
export function App() => {
  const contentContainerRef = useRef();

  return (
    <ContentContainer contentContainerRef={contentContainerRef}>
      <WithBlueBackground contentContainerRef={contentContainerRef}>
      </WithBlueBackground>
    </ContentContainer>
  )
} 
// ContentContainer
export function ContentContainer() => {
  const contentContainerRef = useRef();

  return (
    <div ref={contentContainerRef}>
      // Some content     
    </div>
  )
} 
// WithBlueBackground
export function ContentContainer(props) => {
  useEffect(() => {
    if (props.containerRef && props.contentContainerRef.current) {
      props.contentContainerRef.current.style.backgroundColor = 'blue';
    }
  }, [props.contentContainerRef])

  return <>{ props.children }</>;
} 

This way if I want to have a green background in the content container I can create a new component that sets this style without the ContentContainer having to know about this. This increases the composability of the code which is promote in the react docs.

Nevertheless, passing the refs is a bit ugly.

My question is, is this a sensible pattern and if not is there another way to achieve what I am trying to do here.

Aucun commentaire:

Enregistrer un commentaire