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.
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.
Share asked May 25, 2017 at 10:17 user1177860user1177860 5094 gold badges13 silver badges24 bronze badges 4- " if id equals true" when and How id will be true? – Rohit Choudhary Commented May 25, 2017 at 10:19
- How are you rendering this list? It sounds like you should be using a prop, not manipulating the DOM to add a class after rendering. – Tom Fenech Commented May 25, 2017 at 10:21
- I have some points and each one has an id, onClick the id gets returned – user1177860 Commented May 25, 2017 at 10:21
- Post some code. Your problem statement is not clear! – Rohit Choudhary Commented May 25, 2017 at 10:23
1 Answer
Reset to default 5React 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 ponent:
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>
}