user1177860
user1177860

Reputation: 509

How to add class if id is true in React?

I have a list as follows:

<div id="123" className="panel"></div>
<div id="456" className="panel"></div>
<div id="789" className="panel"></div>
<div id="101" className="panel"></div>

So if id equals true add class open, if false remove open.

Is this possible in react, I've tried using ref but that hasn't worked.

Upvotes: 2

Views: 6156

Answers (1)

Jonny Buchanan
Jonny Buchanan

Reputation: 62793

React handles making the necessary changes to the DOM based on what you render, so instead of thinking in terms of adding and removing classNames when state changes, think in terms of how your render method's output changes.

e.g. if you have some selectedId state which represents the currently-selected id:

render() {
  let {selectedId} = this.state
  return <div>
    <div id="123" className={'panel' + (selectedId === '123' ? ' open' : '')}>...</div>
    <div id="456" className={'panel' + (selectedId === '456' ? ' open' : '')}>...</div>
    ...
  </div>
}

That gets tedious to repeat if you're rendering these manually instead of based on a list of things, so you can break some of the implementation detail out into another component:

function Panel({children, id, open}) {
  let className = 'panel'
  if (open) className += ' open'
  return <div id={id} className={className}>{children}</div>
}

render() {
  let {selectedId} = this.state
  return <div>
    <Panel id="123" open={selectedId === '123'}>...</Panel>
    <Panel id="456" open={selectedId === '456'}>...</Panel>
    ...
  </div>
}

Upvotes: 5

Related Questions