Home > database >  How to set parent node style in React?
How to set parent node style in React?

Time:10-09

I try to set parent node background color like this, but does not work, why?

<div
  onl oad="this.parentNode.style.background = 'yellow';"
>

Found here the inspiration: https://www.w3schools.com/jsref/prop_node_parentnode.asp


The main challange here is this: Make absolute positioned div expand parent div height

I have a parent div with position relative and a child div with position absolute, and I would set the parent height the same as the child.

This post above tells, it can be done only with Javascript, but there is no exact steps for it. Would you help? And I have React on top of it.

I thought if I can set color, I will able to set height also. Set color seemed a bit easier in first turn.

CodePudding user response:

Why don't you use useRef hook to get the ref of the node?

const node = useRef(null);
...
<div ref={node} onl oad={() => {
   node.current.parentNode.style.background = 'yellow';
}} />

CodePudding user response:

Unless there's a really good reason to access the div directly, or as a ref, why not just use props?

Edit: I've included an example of how to use useRef to set the parent height using the child's calculated height.

import React, { useState, useEffect, useRef } from "react";

const ParentComponent = () => {
  const [height, setHeight] = useState(null)
  const node = useRef(null)

  return (
    <div
      style={{
        ...(height ? { height: `${height}px` } : {}),
        backgroundColor: 'yellow',
        position: 'relative'
      }}
    >
      <MyComponent setHeight={setHeight} node={node} />
    </div>
  )
}

const MyComponent = ({ setHeight, node }) => {
  useEffect(() => {
    const childHeight = node.current ? node.current.offsetHeight : 0

    setHeight(childHeight), [node.current]
  })

   // sample parent updates when child updates
  const [content, setContent] = useState(['child'])
  useEffect(
    () => setTimeout(() => setContent([...content, 'child']), 1000),
    [content]
  )


  return (
    <div style={{ position: 'absolute', top: 0, left: 0 }} ref={node}>
      {content.map((item, i) => (
        <div key={i}>{item   i}</div>
      ))}
    </div>
  )
}
  • Related