Home > Software design >  Button to show and hide elements by ID only - React Native
Button to show and hide elements by ID only - React Native

Time:03-18

Currently my show and hide items button works perfectly. I have a JSON with multiple inputs, I want that when I click the button it only opens the input that I clicked on. My problem is that if I click on 1 element, the other IDs are shown.

Here is the code for better explanation:

  getInitialState() {
    return {
      show_info: false
    }
  }

  ...

  const ARTags    = this.state.nearbyPlaces.map((item) => {
      const imagen = item.imagen;
      const id = item.id;

      const showInfo = () => {
        this.setState({show_info: !this.state.show_info});
      };

      return (    
      ...

      <ViroImage 
        onClick={showInfo} 
        // onClick just for this id
        width={1.5} 
        height={1.5} 
        source={{uri: imagen}} 
        position={[0,-1.5,0]}
        style={ {borderRadius: 1, borderWidth: 0.5, borderColor: '#ffffff'}}

      />

      { this.state.show_info &&
        <ViroImage
          height={2}
          width={4}
          position={[coords.x, 5, coords.z]}
          placeholderSource={require("./res/qr/local_spinner.jpg")}
          source={{uri: imagen_1}} 
        />
      }
      ....

That's just a snippet of my code. That's the important part.

As you can see, I iterate through all the elements with "ARTags". The button changes state to hide and show. If I click they show and hide all at the same time.

I repeat: I only want to show and hide the ID of that button that I clicked.

CodePudding user response:

  getInitialState() {
    return {
      show_info: false
    }
  }

  ...

  const ARTags    = this.state.nearbyPlaces.map((item) => {
      const imagen = item.imagen;
      const id = item.id;

      const showInfo = (itemid) => {
        // set state to item.id
        this.setState({show_info: itemid});
      };

      return (    
      ...

      <ViroImage 
        onClick={ () => showInfo(id) } {/* pass items id to showInfo */}
        // onClick just for this id
        key={id}
        width={1.5} 
        height={1.5} 
        source={{uri: imagen}} 
        position={[0,-1.5,0]}
        style={ {borderRadius: 1, borderWidth: 0.5, borderColor: '#ffffff'}}

      />

      { 
        // check state equals this item's id
        this.state.show_info === id &&
        <ViroImage
          key={`show${id}`}
          height={2}
          width={4}
          position={[coords.x, 5, coords.z]}
          placeholderSource={require("./res/qr/local_spinner.jpg")}
          source={{uri: imagen_1}} 
        />
      }
      ....
  • Related