Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
How to set parent node style in React?

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

<div
  onLoad="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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

const node = useRef(null);
...
<div ref={node} onLoad={() => {
   node.current.parentNode.style.background = 'yellow';
}} />
about 4 years ago · Juan Pablo Isaza Report

0

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>
  )
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!