Neff
Neff

Reputation: 189

How correctly Open "div" by ID ReactJS

I would like to explain my problem of the day.

for simplicity. , I map a bdd,

I display the result in a card, it creates several card,

I have a button when I click it opens the rest of the map.

my problem and the next one, when I click it opens all the cards.

I would only like to open by ID

How can I fix this issue?thx all

make room for the code

constructor(props) {
super(props);
this.state = {
  isToggle: false
    }; 
 
this.handleClick = this.handleClick.bind(this);
}

   handleClick = (id) => {
    this.setState({isToggle: !this.state.isToggle });
  }

chat.id = MyMap

  return (
         <div key={chat.id}>
                <div>
                    <div key={chat.id}>
                        <Button onClick={() => {this.handleClick(chat.id)}}> {chat.id}</Button>                          
                    </div>
                </div>

  <div style={{display: this.state.isToggle ? 'block': 'none'}} key={chat.id}>     
  <p> {chat.a} </p> 
   </div>

Upvotes: 0

Views: 286

Answers (1)

Jimmy-P
Jimmy-P

Reputation: 151

Currently, your isToggle is a boolean and all your divs are setting their display css prop to 'block' or 'none' based on that boolean.

What I've done in similar cases is set the isToggle to be a number value (initialstate to -1 or some value that will never match the chat.id), then in your div style you can do

{{display: this.state.isToggle === chat.id ? 'block': 'none'}}

Then in your handleClick you do

handleClick = (id) => {
     this.setState({isToggle: id });
   }

If you wanted to be able to toggle the item on click when it's already active, you could do

  handleClick = (id) => {
         this.setState({isToggle: this.state.isToggle === id ? -1 : id });
       }

This assumes your chat.id is a number value but you could do the same with a string value and set the initial state to "".

Upvotes: 1

Related Questions