Home > database >  How to extract a property value of a child node in a styled component and pass it as props
How to extract a property value of a child node in a styled component and pass it as props

Time:01-13

I am using multiple instances of the 'Icons' component. I was trying to access and use width of the 'a' tag inside the 'Icons' styled component(Here 'a' tag is inside 'Icons' component). Since the content of 'a' tag changes its width also changes. That is why I want to use the width of the 'a' tag inside each 'Icons' component.

import React from "react";
import styled from "styled-components";
import home from "../images/home-icon.svg";
import search from "../images/search-icon.svg";

const Header = () => {
  return (
    <Navbar>
      <Icons imgUrl={home}>
        <div className="special-underline"></div>
        <a className="text-container" href="/">HOME</a>
      </Icons>
      <Icons imgUrl={search}>
        <div className="special-underline"></div>
        <a className="text-container" href="/">SEARCH</a>
      </Icons>
    </Navbar>
  );
};
const Icons=styled.div`
//css styling 
//here I want to access and use width of the anchor component of that Icons component
`

I tried using useRef hook and referencing the 'a' tag but it didn't work. I just could not figure out how to do it.

CodePudding user response:

You can style Icons width dynamically adding width: fit-content.

I wrote a similar example to your code, replacing Icons component with a div with class Icons, but the general idea applies to styled components.

*Edit: the width of the div with class special-underline will also adjust accordingly and be the same as of the a tag. I edited the snippet below to show this.

.Icons {
  width: fit-content; /* <- Here */
  background-color: red;
  margin: 10px;
}

.special-underline {
  background-color: blue;
  height: 2px;
}
<div >
  <div ></div>
  <a>HOME</a>
</div>

<div >
<div ></div>
  <a>SEARCH</a>
</div>

  • Related