Home > Enterprise >  Can react simply change CSS style by selector that's defined elsewhere
Can react simply change CSS style by selector that's defined elsewhere

Time:10-29

To start, I am working with react-swipe-to-delete-component, but I feel that should make little difference in the question.

I am trying to change the background-color property of a "built out" element. I have no control over the class name as the plugin uses it, and I cannot assign it (I think) a separate class name as it stands. Is there a way to change the style of a element solely based on selector, like in vanilla JavaScript?

I have this element <SwipeToDelete>. It builds out a div that I need to access by the selector:

<div >
    <div >

And thus I need to be able to access

.swipe-to-delete .js-delete

as a selector.

Is there a way like in JS IE document.getElementsByClassName('.swipe-to-delete .js-delete')[0].style.background-color = "#FFF")

I need to change the background color based on which function is called:

const [isRight, setRight] = useState(false);
const [isLeft, setLeft] = useState(false);


const onLeft = (...args) => {
    // Make Mask Red with Icon
    console.log('Set left to true');
    setLeft(true);
}
const onRight = (...args) => {
    // Make Mask Green with icon
    console.log('Set right to true');
    setRight(true);
}


<SwipeToDelete
  onLeft={onLeft}
  onRight={onRight}
  >

This works.. I just don't know how to incorporate this pseudo statement

isRight ? '.swipe-to-delete .js-delete'.backgroundColor="green" : ''

Since I can't access <SwipeToDelete>'s inner workings to set a class name somewhere, without modifying the node-module code. I really am stuck here.

I just want to simply change the background color of .swipe-to-delete .js-delete depending on right or left function. Am I looking at this the wrong way?

CodePudding user response:

There is a classNameTag prop you can use to define a className on the wrapper element for <SwipeToDelete> (the element with className="swipe-to-delete").

Based on the swipe direction you set the className accordingly:

<SwipeToDelete
  classNameTag={isRight ? "is-right" : isLeft ? "is-left" : ""}
  onLeft={onLeft}
  onRight={onRight}
>

And styling with CSS:

.swipe-to-delete.is-right .js-delete {
  background-color: green;
}
.swipe-to-delete.is-left .js-delete {
  background-color: red;
}
  • Related