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 !!
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%;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With