score:2

Accepted answer

you can perform that by replacing in ternary operator '' by null which will completely hide the class attribute when it's set to null

class app extends react.component {
  constructor(props) {
    super(props);
    this.state = {
      istrue: false
    }
    this.togglestate = this.togglestate.bind(this);
  }
  
  togglestate () {
    this.setstate({istrue: !this.state.istrue});
  }
  
  render() {
    return (
      <div classname="app">
        <h1 classname={ this.state.istrue ? 'primary' : null }>{ this.state.istrue ? 'selva' : 'ganapathi'}</h1>
        
        <button onclick={this.togglestate}>toggle</button>
      </div>
    );
  }
}

reactdom.render(<app />, document.getelementbyid('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

enter image description here

score:0

import react from 'react';
import logo from './logo.svg';
import './app.css';

let j = {}
if(false) {
  j.classname='primary'
}

function app() {
  return (
    <div classname="app">
      <h1 {... j}>{ false ? 'selva' : 'ganapathi'}</h1>
    </div>
  );
}

export default app;

any one tell me how it works?

score:1

should be null instead of empty string

<h1 classname={ istrue ? 'primary' : null}>...

score:1

in addition to other answers in the thread you can also do this concisely as this:

<h1 classname={ istrue && 'primary' }>{ false ? 'selva' : 'ganapathi'}</h1>

this works pretty much the same way:

  • if istrue is true then the second part of the expression is checked and the entire expression evaluates to primary.

  • if istrue evaluates to false, react sets classname={false} and it won't be set in your dom.

score:1

import react, { usestate } from 'react';
import logo from './logo.svg';
import './app.css';

function app() {
  const [istrue, settrue] = usestate(false);
  return (
    <div classname="app">
      <h1 classname={ istrue ? 'primary' : ''}>
        { istrue ? 'selva' : 'ganapathi'}
      </h1>
    </div>
  );
}

export default app;

score:2

you could pass null or undefined to your classname to remove the prop.

under the hood, react checks for those values and removes the prop for null and undefined.

<h1 classname={ istrue ? 'primary' : null}>{ false ? 'selva' : 'ganapathi'}</h1>

or

<h1 classname={ istrue ? 'primary' : undefined}>{ false ? 'selva' : 'ganapathi'}</h1>


Related Query

More Query from same tag