Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react stateless component with onClick issue

Tags:

reactjs

I have a stateless component and i want to be able to click on the image and redirect it to a new page. The issue that i am having is that i cannot get onClick to work correctly. I was trying to write a function within the onClick = {this.ProjectSelected} but this will not work. Do i have to pass a function (onClick) from the parent to child component? If so how do i do that? I am able to log the project id to the console. Thanks for the help.

const projectListTemplates = (props) => {
    const { classes } = props;
    return (
        <div>
            <div className={classes.root}>
                <GridList className={classes.gridList}>
                    <GridListTile key="Subheader" cols={2} style={{ height: 'auto' }}>
                        <Subheader component="div">Projects</Subheader>
                    </GridListTile>
                    {props.data.map(item => (
                        <GridListTile key={item.image}>
                            <img src="./images/Project/1.jpg" alt={item.title} />
                            <GridListTileBar
                                title={item.title}
                                subtitle={<span> {item.name}</span>}
                                onClick={()=>console.log(`this project was clicked ${item.id}`)}
                                >

                                </GridListTileBar>
                            />
                            <ProgressBar now={60} />
                        </GridListTile>
                    ))}
                </GridList>
            </div>
        </div>
    );
like image 223
Great Khan 2016 Avatar asked Feb 28 '26 03:02

Great Khan 2016


1 Answers

In stateless component we are not defining any local property like state or methods. We have only props and rendering data based on props. We have only props events to trigger. So we have to pass a event function from parent component in order to handle click event. If you want to keep click event locally, convert component to stateful (Class).

Stateless

const ProjectListComponent = (props) => {
  const { onClick } = props
  return (
    <button onClick={onClick}>Click me</button>
  )
}

class AppComponent extends Component {
  handleClick() {
    console.log('clicked')
  }

  render() {
    return (
      <ProjectListComponent onClick={this.handleClick} />
    )
  }
}

Stateful

class ProjectListComponent extends Component {
  handleClick() {
    console.log('clicked')
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    )
  }
}
like image 59
Kishan Mundha Avatar answered Mar 02 '26 16:03

Kishan Mundha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!