~/reactjs/reactjs-how-pass-methods-components-pass-arguments-method.md

ReactJS - How to pass method to component and how to pass arguments to method

2 min readJune 26, 2020by Gorav Singal#reactjs
// TL;DR

Pass a parent component's method as a prop to a child component, and use arrow functions or bind() in the child to pass arguments back when invoking the method.

ReactJS - How to pass method to component and how to pass arguments to method

Introduction

In the ReactJS project, you are having aa parent component and a child component. Let’s assume, we have a Movie and MovieList component.

MovieList is a parent component and is maintaining the list of movies. I want to have the add/remove method in this component. So, this is the correct place to have the remove method. But, this method will be called from the child component: Movie.

We will see how to pass the method reference from parent component to child component and how child component uses that method and pass the argument to the parent component.

Parent Component - MovieList

import React, { Component } from "react";
import Movie from "../Movie";

export default class TourList extends Component {
  state = {
    movies: [
      {
        id: 123,
        name: 'Test 1'
      },
      {
        id: 234,
        name: 'Test 2'
      }
    ]
  };
  removeMovie = (id) => {
    const { movies } = this.state;
    const filteredMovies = movies.filter(movie => movie.id !== id);
    this.setState({
      tours: filteredMovies
    });
  };
  render() {
    return (
      <section>
        {this.state.movies.map(movie => (
          <Movie key={movie.id} movie={movie} removeMovie={this.removeMovie} />
        ))}
      </section>
    );
  }
}

In this parent component, we are having an array of movies. And is rendering the Movie component from this component. This parent component has a method removeMovie which takes an argument movie-id. We are passing this method reference to Movie component via props.

Child Component - Movie

import React, { Component } from "react";
export default class Movie extends Component {
  render() {
    const { id, name } = this.props.movie;
    const { removeMovie } = this.props;

    return (
      <article>
        <h2>{name}</h2>
        <span onClick={() => removeMovie(id)}>
          <i className="fas fa-window-close" />
        </span>
      </article>
    );
  }
}

Note the interesting things:

  • We are accepting props. No need to write a constructor for this.
  • We are getting the values and the reference of removeMovie method.
  • In the render method, we have to configure this method on the click of an icon.
  • Note, we can not write removeMovie(id) as it will call the method. So, the trick is to write a method in which we are calling the reference method.

This is a very helpful trick in passing the reference of methods to some lower levels of components.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS setState is Asynchronous setState() method in ReactJS class components…

ReactJS - How to restrict data type for different kind of data

ReactJS - How to restrict data type for different kind of data

Introduction Javascript is not a strict type language. We can use a variable to…

ReactJS - How to create ReactJS components

ReactJS - How to create ReactJS components

Introduction In this post, we will talk about basic of how to create components…

ReactJS - Basic Form Handling and Form submission

ReactJS - Basic Form Handling and Form submission

Introduction Lets take a look at how forms are being handled in ReactJS. We will…

ReactJS - 3 ways to Import components in ReactJS

ReactJS - 3 ways to Import components in ReactJS

Introduction In this post, we will discuss 3 different ways to import a…

ReactJS - How to use conditionals in render JSX

ReactJS - How to use conditionals in render JSX

Introduction In this post, I will show several ways to use conditionals while…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…