Skip to content Skip to sidebar Skip to footer

Is There A Way To Change The Classname Of An Already Existing React Component?

I have a react component (c1) which renders another react component (c2) which renders another react component (c3). I want to change the 'className'of c3 when a user presses a rad

Solution 1:

You can do it without using refs.

functionComponent1() {
  const [name, setName] = React.useState('disabled')
  
  functionhandleOnChange() {
    setName(previous => previous === 'disabled' ? 'enabled' : 'disabled')
  }
  
  return (
    <div><label>Change class name</label><inputtype="checkbox"onChange={handleOnChange} /><Component2mainClass={name} /></div>
  )
}

functionComponent2({ mainClass }) {
  return<Component3mainClass={mainClass} />
}

functionComponent3({ mainClass }) {
  return<divclassName={mainClass}>Hello World</div>
}

ReactDOM.render(<Component1 />, document.querySelector('#root'))
.disabled {
  color: #666;
}

.enabled {
  color: #00ff00;
}
<scriptcrossoriginsrc="https://unpkg.com/react@16/umd/react.development.js"></script><scriptcrossoriginsrc="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><divid="root"></div>

Post a Comment for "Is There A Way To Change The Classname Of An Already Existing React Component?"