DEV Community

Cover image for Adding a method to a class component
Cesare Ferrari
Cesare Ferrari

Posted on

3

Adding a method to a class component

How to pass class component method to child component in React

Sometimes we need to add a method to a class component and pass it down to its child component.
For example, we may have a GroceryList component that has a child component called GroceryItem.
We define a toggleItem() method in GroceryList that we want to trigger from GroceryItem. How do we do that?

Let's first define the method in the parent component.
The way we add a method to a class component is to simply create an identifier inside the class definition and assign an arrow function to it.
The identifier will be the name of the method we call.

class `GroceryList` extends React.Component {
  toggleItem = itemId => {
    // perform a toggle action
  }
}

To use this method in the child component, we need to pass it down via props:

<GroceryItem item={item} toggleItem={this.toggleItem} />

Inside the child component we then use this method in an onClick event:

<div onClick={ () => {props.toggleItem(props.item.id)} } />
  Click me
</div>

When we click on the <div> element now we trigger the onClick event that will call toggleItem() in the parent component, passing the item id as an argument.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay