React Color Picker on bootstrap navbar

508 Views Asked by At

I added a ColorpickerBackground component to change the body background color of my app. This is working well...

My problem is when I add a new component ColorpickerNavbar to change the color of my bootstrap (4) navbar it doesn't work as expected. The color is changed after save, but the goal is to see the live change...

The !important is needed, but I dont know how to set it, and IF I have to set it in the react component....

This is the html of my navbar:

<nav class="navbar navbar-expand-lg navbar-custom navbar-dark bg-dark navbar-fixed-top" style= "background: <%= prefered_navbar_color %>!important;" id="my_nav">
 ...
</nav>

This is the html where the colorpicker appears:

<%= f.hidden_field :navbar_color %>
                            <%= react_component('ColorpickerNavbar', { navbar_color: prefered_navbar_color, selector: 'customization_navbar_color'} ) %>
                        </div>

ColorpickerNavbar.js

import React from "react"
import PropTypes from "prop-types"

import { SketchPicker } from 'react-color'


class ColorpickerNavbar extends React.Component {

  constructor(props) {
    super(props);

    this.state = { selector: props.selector };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (navbar_color) => {
    let myNav = document.getElementById("my_nav")
    myNav.style.background = navbar_color.hex;

    let elem = document.querySelector('#' + this.state.selector);

    elem.value = navbar_color.hex;
  }


  render(){
    return  (
        <React.Fragment>
          <SketchPicker navbar_color={this.props.navbar_color}
                        onChange={this.handleChange}/>
        </React.Fragment>
    );
  }
}

ColorpickerNavbar.propTypes = {};

export default ColorpickerNavbar
1

There are 1 best solutions below

0
On

use the method setAttribute:

myNav.setAttribute('style', 'background: ' + navbar_color.hex + ' !important;')