StochasticNerd StochasticNerd - 1 month ago 9
Javascript Question

Rendering a component onClick in React

I'm rank new to React and to javascript in general. Thus the question.

I've a list of images being displayed in a React component. What I'm trying to achieve is to define a method to handle the onClick method on any of these images and render a new component as an overlay. This is my code.

class Viewer extends React.Component{

constructor(props){
super(props);
this.state = {
images : ImageList
};

}

componentDidMount(){

}
handleClick(mediaId, event){
event.preventDefault();
render(){
<MyNewComponent mediaId=mediaId />
}
}

render(){
return (
<div className="row">
<div className="image-viewer">
<ul className="list-inline">
{this.state.images.map(function (image) {
return (<li key={image.mediaId}><a href="#" onClick={this.handleClick.bind(image.mediaId, event)}><img src={image.src}
className="img-responsive img-rounded img-thumbnail"
alt={image.mediaId}/></a></li>);
})}

</ul>
</div>
</div>
);
}
}
export default Viewer;


This clearly is wrong and throws up a bunch of errors. Can someone point me in the right direction.

Answer

Here how to handle the click event and show the overlay

class Viewer extends React.Component{

  constructor(props){
    super(props);
    this.state = {
      images : ImageList,
      mediaId : 0
    };
    // Bind `this`
    // See "Binding to methods of React class" link below
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount(){ }

  handleClick(event){
    event.preventDefault();
    // Get the value of the `data-id` attribute <a data-id="XX">
    var mediaId = event.currentTarget.attributes['data-id'].value;
    // Set the state to re render
    this.setState({ mediaId }); // ES6 shortcut
    // this.setState({ mediaId: mediaId }); // Without shortcut
  }

  render(){
    // Set a variable which contains your newComponent or null
    // See "Ternary operator" link below
    // See "Why use null expression" link below
    var overlay = this.state.mediaId ? <MyNewComponent  mediaId={this.state.mediaId} /> : null;

    return (
      <div className="row">
        <div className="image-viewer">
          { overlay }
          <ul className="list-inline">
            {this.state.images.map(image => {
              return (<li key={image.mediaId}><a href="#" onClick={this.handleClick} data-id={image.mediaId}><img src={image.src}
                                                               className="img-responsive img-rounded img-thumbnail"
                                                               alt={image.mediaId}/></a></li>);
            }).bind(this)}

          </ul>
        </div>
      </div>
    );
  }
}
export default Viewer;

Documentation