Home > Mobile >  how to get style info from parent element? reactjs css
how to get style info from parent element? reactjs css

Time:09-22

I have a text component inside a button component. I want to change the color of the text automatically according to the color of the button (parent of the text) how can I get the color of the parent element? in my text I have

const MyText = (props) => {
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const styles = window.getComputedStyle(ref.current).getPropertyValue('color');  //test
  }, [ref]);

  return <MyTextStyled ref={ref} {...props} />;   // styled components 
};

const MyPage = () => {
  return (
   <Button> // my button styled components
     <MyText>Button 1</MyText>
   </Button>
  );
};

how to get button background color to change text color? in the current way, I don't have access to the parent's styles, I just have my text

CodePudding user response:

You can add css style to Mytext : color: 'inherit'

CodePudding user response:

Set the state for color in the parent of both components and then drill down the state to both components, also drill down the setColor to component which would change the color. That will solve your issue!

See the example below:

const MyText = (props) => {
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const styles = props.color;  //test
  }, [props.color]);

  return <MyTextStyled ref={ref} {...props} />;   // styled components 
};

const MyPage = () => {
  const [color, setColor] = useState('blue')
  return (
   <Button color={color} setColor={setColor}> // my button styled components
     <MyText color={color}>Button 1</MyText>
   </Button>
  );
};

  • Related