Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the style of a reactjs component by code

Tags:

reactjs

I need to change the style of some child components of a react components. Something like this:

import React, { Component } from 'react';

class Parent extends Component {
   onClickHandler = (event) => {
      this.props.children[0].props.style.marginLeft = "-100%";
   }
   render() {
      <div onClick={this.onClickHandler}>
         {this.props.children}
      </div>
   }
}

export default Parent;

The error i'm getting is:

TypeError: Cannot add property marginLeft, object is not extensible

May you help me guys?

Thanks a lot !!

like image 630
RDV Avatar asked Sep 17 '25 09:09

RDV


1 Answers

The error you are getting is because you cannot modify props, since those are immutable. A simpler approach can be done using plain CSS and simple state management.

With this technique, you need a state variable to know when to add the class modifier. That class modifier is in charge of overriding the styles of the child component.

The JS would look like this:

import React, { Component } from "react";

class Parent extends Component {
  constructor() {
    this.state = {
        bigMargin: false
    };
  }

  onClickHandler = (event) => {
      event.preventDefault();
      this.setState({ bigMargin: true });
  };

  render() {
    return (
        <div className={`parent-class ${bigMargin && 'big-margin'}`} onClick={this.onClickHandler}>
            {this.props.children}
        </div>
    );
  }
}

export default Parent;

And the CSS can be something as simple as this (or as complex as you may want)

.big-margin:first-child {
  margin-left: -100%;
}
like image 166
Yalung Tang Avatar answered Sep 19 '25 23:09

Yalung Tang