Reputation: 21
I'm working on a React Component that acts as a clickable wrapper for other components and the issue I have is that some of the other components have a border-radius which makes the wrapper component stick out in the corners. How I've solved this is by giving the wrapper the same border-radius via a prop, the problem with this approach is that I don't know the border-radius of some components. I've been trying to find a way to get the border-radius attribute value from the child component by using useRef()
and then wrapperRef.current.props.children[0]
but the border-radius value isn't present.
.wrapper {
border: 1px solid black;
display: inline-block;
cursor: pointer;
}
.demo-wrapper {
border: 1px solid black;
border-radius: 24px;
display: inline-block;
cursor: pointer;
}
.child {
width: 200px;
height: 100px;
border-radius: 24px;
background-color: teal;
display: flex;
justify-content: center;
align-items: center;
}
<div>
<p>What i get</p>
<div class="wrapper">
<div class="child"><p>child element</p></div>
</div>
<p>What i want</p>
<div class="demo-wrapper">
<div class="child"><p>child element</p></div>
</div>
</div>
Is there a way to get the border-radius value from the child element? Or is there a way to inherit the border-radius from child to parent element? Or maybe I'm going on about this in the wrong direction entirely and there is a better way to solve this other than setting the same border-radius on parent element?
Upvotes: 2
Views: 414
Reputation: 3178
This solution involves:
Setting a ref
on the wrapper element
Using useEffect
, which runs after the component's rendered:
2.1. Use element.firstChild
on the wrapper ref
, to get a reference to the child's outer html element
2.2 Use getComputedStyle()
to get the child element's border radius
2.3 Set that border radius on the wrapper element, using our ref.
The wrapper then would be:
import { useEffect, useRef } from "react";
const Wrapper = ({ children }) => {
const container = useRef();
useEffect(()=>{
const borderRadius = getComputedStyle(container.current.firstChild).borderRadius
container.current.style.borderRadius = borderRadius
}, [])
return <div ref={container}>{children}</div>;
};
A working example:
Upvotes: 1