Search code examples
cssreactjsreact-hooksattributesstyled-components

Using CSS attr() with styled components in react Hooks


I am trying to use attribute of SkillPer component pers={80} in css content attr function like so:

content: attr(pers) "%";

But content: attr() cannot get the attributes of <SkillPer pers={80}></SkillPer>

Am I missing something there? please help!

<SkillBar className="skill-bar">
    <SkillPer
        className="skill-per"
        pers={80}
        style={{ maxWidth: "80%" }}
    ></SkillPer>
</SkillBar>

export const SkillPer = styled.div`
    height: 12px;
    border-radius: 8px;
    background-color: var(--color-green);
    animation: ${fillBars} 2.5s 1;
    position: relative;
    &::before {
        content: attr(pers) "%"; // here
        position: absolute;
        padding: 4px 6px;
        background-color: #333;
        color: var(--color-white);
        font-size: 15px;
        right: 0;
        transform: translateX(200%);
    }
`;

Solution

  • pers is a prop, so you can access the props in the style body. I believe this should work for you.

    export const SkillPer = styled.div`
      height: 12px;
      border-radius: 8px;
      background-color: var(--color-green);
      animation: ${fillBars} 2.5s 1;
      position: relative;
      &::before {
        content: ${({ pers }) => `"${pers} %"`};
        position: absolute;
        padding: 4px 6px;
        background-color: #333;
        color: var(--color-white);
        font-size: 15px;
        right: 0;
        transform: translateX(200%);
      }
    `;