james
james

Reputation: 570

Updating a div size based on props in react

I'm trying to implement a side nav bar like how it is shown on this website

https://adminlte.io/themes/AdminLTE/index2.html

Now I'm trying to basically emulate the expanded nav bar and mini navbar toggle. However, I'm having trouble updating the size of the navbar in react.

Here is my nav bar component

import React, { Component } from 'react';

class SideNavBar extends Component {

    render() {
        let sideBarStyle = {
            'height': '100%',
            'backgroundColor': 'lightblue',
            'width': "80px",
            'position': 'absolute',
            'top': '0',
            'left': '0'
          }
        setTimeout(() => {
            sideBarStyle["width"] = "300px";
        }, 1000)
        return (
            <div style={sideBarStyle}>
                sidenavbar
            </div>
        );
    }
}

export default SideNavBar;

I put a set timeout there just because I wanted to quickly test if it was possible to expand the div's width from a click event. But I get the following error

TypeError: Cannot assign to read only property 'width' of object '#<Object>'

How do I go about updating an element's size based on click events?

Upvotes: 2

Views: 4620

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

Can you try below.

import React, { Component } from 'react';

class SideNavBar extends Component {
    constructor(props){
      super(props);
      this.state = {
        width : 80
      }
    }
    componentDidMount(){
      setTimeout(() => {
            this.setState({
              width: 300
            })
        }, 1000);
    }
    render() {
        let sideBarStyle = {
            'height': '100%',
            'backgroundColor': 'lightblue',
            'width': this.state.width,
            'position': 'absolute',
            'top': '0',
            'left': '0'
          }

        return (
            <div style={sideBarStyle}>
                sidenavbar
            </div>
        );
    }
}

export default SideNavBar;

One more thing you no need to specify px explicitly in React. Just no is enough. React will take care of px.

Upvotes: 1

Related Questions