Reputation: 19
Now example text with the background will be red color. But I want the class rightElement: after having border-top: color. It should take from const. I don't know how to do that
const color = "red";
<div className='rightElement' style={{backgroundColor: color} >Example </div>
rightElement:after
{
border-top :color ( From const color )
}
Upvotes: 0
Views: 1940
Reputation: 71
In HTML & CSS
.testAfter::after {
content: "->"
}
<div class="testAfter">Something</div>
We can use ::after and other pseudo code like this in css.
So we need external css to use pseudo code in react.
// test.css
.rightElement::after {
content: "-> after";
border-top: 1px solid red;
}
// Test.js
import React from 'react';
import './test.css';
class Test extends React.Component {
render () {
const color = "red";
return(
<div>
<div className='rightElement' style={{backgroundColor: color}} >Example </div>
</div>
)
}
}
export default Test;
Using Inline
render () {
const color = "red";
return(
<div style={{width: '500px', margin: '0 auto', marginTop: '100px'}}>
<div className='rightElement' style={{backgroundColor: color}} >Example </div>
<div style={{borderTop: `10px solid ${color}`}}></div>
</div>
)
}
The trick here is instant of creating new element via ::after or ::before I create new element by my own. But creating new element for only styling purpose is not good(Just my option).
Upvotes: 0
Reputation: 6755
It is not possible to directly access the pseudo element.
However, you could change their style indirectly by adding in a new style element containing new rules.
Try like this to add after css.
const color = "red";
var styleElem = document.head.appendChild(document.createElement("style"));
styleElem.innerHTML = "#rightElement:after {border-top: 1px solid "+color+";}";
<div id='rightElement' style="background-color: green" >Example </div>
Upvotes: 1
Reputation: 1235
See CSS pseudo elements in React. It seems that a best practice is to use separate elements in React instead of pseudo-elements. Could you just do this instead?
<div className='rightElement' style={{backgroundColor: color}}>
Example
<div style={{borderTopColor: color}}></div>
</div>
Upvotes: 0
Reputation: 22265
you looking for this : ? ( https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties )
:root {
--my-color: red;
}
.rightElement {
display: inline-block;
border-top :5px solid var(--my-color);
}
<div class="rightElement" > Example </div>
Upvotes: 0