Search code examples
reactjsjsxreact-props

Pass clicked element's information to a modal as props - Reactjs


I want access properties like id, etc of the clicked item on the modal. How can I pass target properties as props to modal on click.

Below is what I am trying. Unfortunately, the modal shows the targetElement prop as undefined in componentDidMount function of CropperModal

export default class DynamicArticleList extends React.Component {
    
    constructor(){
        super();
         this.state={
            
             targetElement: '',
            
             
        }
     
        this.showModal = this.showModal.bind(this);
        this.hideModal = this.hideModal.bind(this);
 
    }
 
    showModal(e){
        
        this.setState({
            targetElement: e.target.getAttribute("id")
        })
    }
    
    hideModal(e){
        this.setState({
            showing: false,
            showSource: '#',
        })
        
    }
  

 
    


    render() {
      

        return (
       

            <div className="wrapper container-fluid DynamicArticleList">
                <div className="width-control">
                   <img src="../img/journey.jpg" onDoubleClick={this.showModal} id="Img0"/>
                   <CropperModal targetElement={this.state.targetElement}/>                   
                
                </div>
            </div>

        );
    }
}

Solution

  • Here's how I did it. I basically avoided the modal component to render until the click event was processed

    export default class DynamicArticleList extends React.Component {
    
    constructor(){
        super();
         this.state={
             showing: false,
             targetElement: '',
            
             
        }
     
        this.showModal = this.showModal.bind(this);
        this.hideModal = this.hideModal.bind(this);
    
    }
    
    showModal(e){
        
        this.setState({
            showing: true,
            targetElement: e.target.getAttribute("id")
        })
    }
    
    hideModal(e){
        this.setState({
            showing: false,
            showSource: '#',
        })
        
    }
    
    render() {
        return (
            <div className="wrapper container-fluid DynamicArticleList">
                <div className="width-control">
                   <img src="../img/journey.jpg" onDoubleClick={this.showModal} id="Img0"/>
                   {this.state.showing ? <CropperModal targetElement={this.state.targetElement}/> : null}                  
                
                </div>
            </div>
    
        );
    
    
     }
    }