From React Class component to Functional component with hooks

How to pass a Callback as Props in React components?

Before learning how to  Toggle an element and Create a Simple Counter, Control an Input, create a Controlled Form, we had learnt how to pass state as  props to children components.  Let’s learn how to pass a Callback as Props.  This ninth episode, has been inspired by a freeCodeCamp challenge

We will review how to pass a callback as props in a class component and then we will do it in a functional component.

Summary

Reminder: as usual, before starting coding, just check that React, React.Dom libraries and Babel preprocessor have been installed.

Pass a callback as props

We can pass state as props to a child component, but we are not limited to passing data : we can also pass handler functions or any method defined on a React component to a child component. Passing data and functions or methods, we allow child components to interact with their parent components.

In this article, we will build a small App made up of three components: the MyApp component which is parent component will render the GetInput component — that displays an input  — and the RenderInput component — that displays the input value.

A prop called input assigned to the MyApp inputValue state property is passed to the GetInput component and the RenderInput.

An handler method called handleChange is declared in the MyApp component and passed as props to the GetInput component.

First, we will build this small App using class components. Then, we will build it using functional components

Pass a Callback as Props in React Class components.

Before passing a Callback as Props in React functional components, let’s create it in a class component.

Steps to pass a callback as props in React Class components

  1. Install React locally or create a new pen on codepen.
  2. Create the HTML element onto render the component. Give it the id “controlled-form”.

The parent component MyApp

  1. Create a class component which extends React.Component. Name it MyApp.
  2. Add the internal state in the constructor with this.state.
  3. Initialize the state inputValue property at ” (empty string).
  4. Create a handler method named handleChange and pass it the event as argument so when the input value is modified by the user the state input value is set with the event.input.target.
  5. Do not forget to  bind the handleChange method in the constructor.
  6. In the render, insert two child components: GetInput and RenderInput.
  7. Create a prop called input and pass the GetInput and RenderInput the InputValue from state to them.
  8. Create a prop called handleChange and pass the GetInput the handleChange() method to it.

The child component GetInput

  1. Create a class component which extends React.Component. Name it GetInput.
  2. In the render, return an heading h3 whose texte is “Get Input” and an input element.
  3. Assign the props input to its value attribute.
  4. Assign the props handlechange to its onchange attribute. The onChange attribute will call the handleChange() method in its parent via props :  the onChange attribute call the handleChange props which will trigger the handleChange() methods in the MyApp parent component.

The child component RenderInput

  1. Create a class component which extends React.Component. Name it RenderInput.
  2. In the render, return an heading h3 whose texte is “Render Input” and a paragraph element.
  3. Pass the props input to the paragraph to display the input value typed by the user.

Pass a callback as props in React class components code

The final code of passing a callback as props in React class components

class MyApp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: ”
        }
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({
            inputValue: event.target.value
        });
    }
    render() {
        return (
            <div>
                <GetInput
                    input={this.state.inpuValue}
                    handleChange={this.handleChange}
                />
                <RenderInput input={this.state.inputValue} />
            </div>
        );
    }
};
class GetInput extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
                <h3>Get Input:</h3>
                <input
                    value={this.props.input}
                    onChange={this.props.handleChange}/>
            </div>
        );
    }
};
class RenderInput extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
                <h3>Input Render:</h3>
                <p>{this.props.input}</p>
            </div>
        );
    }
};
ReactDOM.render(<MyApp />, document.getElementById(‘callback-props’));

View the final code of passing a callback as props in React class components in a pen

See the Pen
React tricks: Pass a Callback as Props in a class component
by Coding-Tricks (@coding-tricks)
on CodePen.

Pass a Callback as Props in React Functional component

Steps to pass a collaback as props in React Functional components

  1. Install React locally or create a new pen on codepen.
  2. Create the HTML element onto render the component. Give it the id “input”.

The parent component MyApp

  1. Import the useState hook at the beginning of the file import { useState } from 'react';. Remark: when using codepen the import is not allowed, write const { useState } = React; instead.
  2. Create a functional component named MyApp.
  3. Add an internal state property with the useState() hook. Name it inputValue, for example.
  4. Initialize the state at ” (empty string).
  5. In the return of the component function, insert two children components: GetInput and RenderInput.
  6. Create a prop named input and pass the GetInput and RenderInput components the inputValue state.
  7. Create a prop named handleChange and pass the GetInputcomponent the handleChange function.
  8. Create the handlechange function and pass it an event as argument. Call the setInputValue function to update the submitted state property and pass it the event.target.value.

The child component GetInput

  1. Create a functional component named GetInput.
  2. Pass it the props input and handleChange as arguments.
  3. Insert a heading h3 whose text is “Get Input”.
  4. Insert an input element.
  5. Assign it the props input as value attribute.
  6. Assign the props handleChange to its onChange attribute which will trigger the handleChange function in its parent when the user types something in the input field.

The child component RenderInput

  1. Create a functional component named RenderInput.
  2. Pass it the props input as argument.
  3. Insert a heading h3 whose text is “Render Input”.
  4. Insert a paragraph and assign it the props input.

Pass a Callback as props in React Functional components Code

The final code of passing a callback in react functional components

const { useState } = React;
const MyApp = () => {
    const [inputValue, setInputValue] = useState(“”);
    const handleChange = (event) => {
        setInputValue(event.target.value);
    };
    return (
        <div>
            <GetInput
                input={inputValue}
                handleChange={handleChange}
            />
            <RenderInput
                input={inputValue}
            />
        </div>
    );
}
const GetInput = ({input, handleChange}) => {
    return (
        <div>
            <h3>Get Input</h3>
            <input
                value={input}
                onChange={handleChange}
            />
        </div>
    );
}
const RenderInput = ({input}) => {
    return (
        <div>
            <h3>Input render</h3>
            <p>{input}</p>
        </div>
    );
}
ReactDOM.render(<MyApp />, document.getElementById(‘callback-props’));

View the final code of passing a callback as props in react functional components in a pen

See the Pen
React tricks: Pass a Callback as Props with the hook useState
by Coding-Tricks (@coding-tricks)
on CodePen.

In conclusion

Once again, we have tried and managed to transform Pass a callback as props in React class components code into Pass a callback as props in React functional components code.

What it is very important in this article is to notice how the data flows between the components and how the single source of truth remains the state of the parent component. When typing in the input field in the GetInput component, the handler method is called in its parent via the props which updates the input in the state of the parent which is passed as props to both children. Do not forget that putting the data in the higher component state allow us to use this state as pops in all its children components!

As you can see, as soon as the user type a letter in the input field, the letter is displayed below. Add a debounce function could be an interesting exercise. If you do not remember how to do that, refer to the previous article Improve performance in React components with useEffect and debouncing.

In the next episode of the series From React Class component to Functional component with hooks, we will discover how to add Event Listeners.

Haut de page