Search code examples
cssreactjsinline-stylesslick.js

React Inline Style - How to style automatic generated tags?


I'm using Slick Carousel with React but i need modify some styles of some divs which are automatically created by Slick.

import React from 'react';
import Slider from 'react-slick';

export default class Slider extends React.Component {
    render: function () {
        var settings = {
            dots: true,
            infinite: true,
            speed: 500,
            slidesToShow: 1,
            slidesToScroll: 1
        };

        return (
            <Slider {...settings}>
                <div><h3>1</h3></div>
                <div><h3>2</h3></div>
                <div><h3>3</h3></div>
                <div><h3>4</h3></div>
                <div><h3>5</h3></div>
                <div><h3>6</h3></div>
            </Slider>
        );
    }
});

Because i set dots = true, so the dots will be displayed below my slider. But i need to change its style. With inline style, how can i do that ?

Thanks !


Solution

  • edit - as noted later by Hung Nguyen slick has a dotsClass in their settings API so that might be simpler. Thanks Hung!

    • When something like that is not available though, this still works for grabbing unknown elements after render:

    Using the lifecycle event componentDidMount allows you to look for the elements after render(). You can use ReactDOM.findDOMNode() to get the real DOM elements (not the React virtual DOM). Then just identify the elements you need and change their style.

    Demo using a Fork of react-slick

    var ReactSlickDemo = React.createClass({
      componentDidMount: function() {
        //find the unknown slider elements here
        var elements = ReactDOM.findDOMNode(this).children[0];
        //modifying styles
        elements.style.border = "5px solid red";
      },
    
      render: function() {
        var settings = {
          dots: true
        }
        return (
          <div className='container'>
            <Slider {...settings} >
              <div><img src='http://placekitten.com/g/400/200' /></div>
              <div><img src='http://placekitten.com/g/400/200' /></div>
              <div><img src='http://placekitten.com/g/400/200' /></div>
              <div><img src='http://placekitten.com/g/400/200' /></div>
            </Slider>
          </div>
        );
      }
    });
    
    ReactDOM.render(
      <ReactSlickDemo />,
      document.getElementById('container')
    );