Home > Software design >  Can a React JS class be called via an onClick listener in another Component?
Can a React JS class be called via an onClick listener in another Component?

Time:10-16

I have code that looks like so:

import React from "react";
import Overlay from "./Overlay";

export default class TagListItem extends React.Component {

    render() {
        return(
            <div className={'tag'} onClick={() => <Overlay data={this.props}/>}>
                {this.props.tag}
            </div>
        )
    }
}

Using breakpoints I've been able to figure out that the onClick event triggers, but my Overlay class doesn't get triggered (Nothing actually happens in Overlay when 'tag' is clicked). Here's my Overlay code, what am I getting wrong? Is it not possible to call a class via an onClick?

import React from "react";
import ImagesAndTags from "./ImagesAndTags";

export default class Overlay extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            manifest: [],
        }
    }
    render() {
        const imagesAndTags = new ImagesAndTags();
        imagesAndTags.getManifest(this.props.imageName, this.props.tag)
            .then(manifest => {
                this.setState({manifest: manifest})
            })
        return(
            <div className={'overlay'}>
                {this.state.manifest}
            </div>
        )
    }
}

CodePudding user response:

Nope you can't do that

export default class TagListItem extends React.Component {

    render() {
        return(
            <div className={'tag'} onClick={() => <Overlay data={this.props}/>}>
                {this.props.tag}
            </div>
        )
    }
}

instead you can make a state to control whether you want to open the overlay or not

export default class TagListItem extends React.Component {
      this.state ={
    overlay = false
}
    render() {
        return(
            <div className={'tag'} onClick={() => this.setState(state=>{overlay : !state.overlay})}>
    {this.state.overlay && <Overlay data={this.props}/>}
                {this.props.tag}
            </div>
        )
    }
}
  • Related