Home > Enterprise >  How can I use CSS Pseudo-elements styling inside React JSX to pass variables?
How can I use CSS Pseudo-elements styling inside React JSX to pass variables?

Time:12-22

The following code is for adding a badge to a card.

CSS Working code:

.card::before {
  position: absolute;
  content: "";
  background: #283593;
  height: 18px;
  width: 18px;
  top: 2.5rem;
  right: -0.7rem;
  z-index: -1;
  transform: rotate(45deg);
}

.card::after {
  position: absolute;
  content: "Sample Name";
  top: 11px;
  right: -14px;
  padding: 0.5rem;
  width: 11rem;
  background: #3949ab;
  color: white;
  text-align: center;
  box-shadow: 4px 4px 15px rgba(26, 35, 126, 0.2);
}

I want to pass variables in the form of JSX inside the CSS styling like below:

<div
  className="card"
  styleBefore={{
    position: "absolute",
    content: "",
    background: "#283593",
    height: "18px",
    width: "18px",
    top: "2.5rem",
    right: "-0.7rem",
    zIndex: "-1",
    transform: "rotate(45deg)",
  }}
  styleAfter={{
    position: "absolute",
    content: `- ${this.props.name}`,
    top: "11px",
    right: "-14px",
    padding: "0.5rem",
    width: `${this.props.name.length}rem`,
    background: "#3949ab",
    color: "white",
    textAlign: "center",
    boxShadow: "4px 4px 15px rgba(26, 35, 126, 0.2)",
  }}
>

Instead of "styleBefore" and "styleAfter" (Invalid fields) that I used above, how can I replicate ".card::before" and ".card::after" of css in JSX?

CodePudding user response:

you can use styled components or makeStyles from mui/styles

CodePudding user response:

You can use from styled-components:

import React from 'react';
import styled from 'styled-components';

const Div = styled.div`
&::before{
  position: absolute;
  content: "";
  background: #283593;
  height: 18px;
  width: 18px;
  top: 2.5rem;
  right: -0.7rem;
  z-index: -1;
  transform: rotate(45deg);
}
&::after{
  position: absolute;
  content: ${props => props.name};
  top: 11px;
  right: -14px;
  padding: 0.5rem;
  width: 11rem;
  background: #3949ab;
  color: white;
  text-align: center;
  box-shadow: 4px 4px 15px rgba(26, 35, 126, 0.2);
}
`;

class App extends React.Component {
.
.
.
render(){
   return(
          <Div name=""></Div>
);
}
}

Of course, You must install the requirements:

yarn add styled-components

More information about styled-components

Tell me, if this helped you:)

  • Related