Search code examples
javascriptcssreactjscomponents

How to change properties of nested elements in react-star-ratings


My task is to implement styled with classNames (not inline/attributes) star rating using react-star-ratings. Trying to change properties of nested elements of this component (finding names of classes using DOM), but there is no solution...

  1. I'm imported this component and wrapped it in a div-block (I'm using TS and this component has strange type - so I can't use classNames in attributes of this component) If you have to say something about this issue, I will be happy... TSX code
  2. Found my div-block in DOM and chose nested devtools
  3. Created SCSS module for change of this classes (added !important, cause component has some inline styles) SCSS code

So, there is no result. As u can see on DOM picture - class Rating is added, but there is no changes with nested elements.


Solution

  • As you've noticed, The react-star-rating library does not seem to support styling via the className attribute - in fact, it is not part of the Props for the StarRating component.

    However, your approach of wrapping it in another container and crafting selectors to target the inner elements should work - to some degree enter image description here - but then there seems to be no way of differentiating between filled or empty stars...

    If you must use react-star-rating (there are other alternatives - or you could build your own), a better approach could be to use CSS custom properties:

    <div className="my-custom-rating">
      <StarRatings
        rating={rating}
        starRatedColor="var(--star-rated-color)"
        starEmptyColor="var(--star-empty-color)"
        changeRating={setRating}
        numberOfStars={6}
        name="rating"
      />
    </div>
    
    .my-custom-rating {
      --star-rated-color: rebeccaPurple;
      --star-empty-color: whitesmoke;
    }