RainbowShout
RainbowShout

Reputation: 31

How to change attribute of a React Element

I've created a render method which adds a number of dynamically created 'InfoWindow' elements to a Class based object.

Each InfoWindow element has a unique ID and key.

I also have a number of 'Marker' elements with corresponding ids and keys.

Currently all Infowindows have a prop of 'visible={false}'

When I click a Marker a function is called which outputs the Marker ID.

I'd like to find the InfoWindow with the relevant ID and set visibility = {true}

Is there a way to find the relevant InfoWindow element using its key or ID, and then call setAttribute (or equivalent)?

I've tried searching the DOM for the ID but Google Maps doesn't render that way, so I'm thinking there must be a more React-y way to do this?

let visibilityFunction = () => {
  this.changeVisibility(01);
};

changeVisibility = (e) => {
    console.log(e);
    //this currently outputs the ID (01)
}


render() {

    return( 
        <Parent>
            <InfoWindow
                visible={false} 
                key={01-iw} 
                id={01-iw}
             />
            <Marker
                key={01} 
                id={01}
                onClick={visibilityFunction}
             />
        </Parent>
    );
}

Upvotes: 2

Views: 10718

Answers (1)

John Ruddell
John Ruddell

Reputation: 25842

Like I was saying in the comments. Use state here to update the visibility.

class MyComponent extends React.Component {
  state = { visibleWindows: {}, currentWindows: [1] };

  changeVisibility = id => {
    this.setState(prevState => ({
      visibleWindows: {
        ...prevState.visibleWindows,
        [id]: !prevState.visibleWindows[id]
      }
    }));
  };
  render() {
    const { currentWindows, visibleWindows } = this.state;
    return (
      <div>
        {currentWindows.map(win => (
          <ChildWindow key={win} id={win} isVisible={!!visibleWindows[win]} onChange={this.changeVisibility} />
        ))}
      </div>
    );
  }
}

class ChildWindow extends React.Component {
  changeVisibility = () => {
    this.props.onChange(this.props.id)
  }
  render() {
    <React.Fragment>
      <InfoWindow
        visible={this.props.isVisible}
        key={`${win}-iw`}
        id={`${win}-iw`}
      />
      <Marker
        key={win}
        id={win}
        onClick={this.changeVisibility}
      />
    </React.Fragment>
  }
}

Here's a rudimetary example for you to poke around with :)

Upvotes: 3

Related Questions