Understanding the Control Props Pattern in React: A Simple Example

Spread the love

Hello friends, In this post we are going to implement control props pattern is react. When you work on a react project, you might have a use case in which you have to pass the component state and event handlers outside the component. This is exactly the use case which can be solved using control props patten. You can download the example code from react-design-pattern/control-props-example at main ยท navinprasadofficial/react-design-pattern (github.com)

Definition

The Control Props pattern is a design pattern in React that involves passing both the value and an event handler from the parent component to a child component. By doing so, the parent component maintains control over the child’s state, enabling it to modify or retrieve the child’s value as needed.

Example demonstrating the control props pattern.

Create new Project using below command and add components folder in src directory.

npx create-react-app control-props-example --template typescript

Create a new component file “TextInputBox.tsx” and add below code in it.

import React from "react";

interface TextInputBoxProps {
  value: string;
  onChange: (value: string) => void;
  onClear: () => void;
}

export const TextInputBox: React.FC<TextInputBoxProps> = (
  props: TextInputBoxProps
) => {
  const { value, onChange, onClear } = props;

  const onChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    onChange(e.target.value);
  };

  const onClearHandler = () => {
    onClear();
  };

  return (
    <div>
      <input type="text" value={value} onChange={onChangeHandler} />
      <button onClick={onClearHandler}>Clear</button>
    </div>
  );
};

export default TextInputBox;

The above code defines a functional component called TextInputBox in TypeScript. It expects three props: value, onChange, and onClear. The value prop represents the current value of the input field, while onChange and onClear are event handlers for input changes and clearing the input, respectively.

Inside the component, an input element is rendered with the value prop bound to its value attribute. The onChange event handler is called when the input value changes, and the onClear event handler is triggered when the “Clear” button is clicked.

Create new component file Parent.tsx and add below code in it.

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

const Parent: React.FC = () => {
  const [textInputBoxValue, setTextInputBoxValue] = React.useState<string>("");

  const onTextInputBoxChange = (value: string) => {
    setTextInputBoxValue(value);
  };

  const onTextInputBoxClear = () => {
    setTextInputBoxValue("");
  };

  return (
    <>
      <TextInputBox
        value={textInputBoxValue}
        onChange={onTextInputBoxChange}
        onClear={onTextInputBoxClear}
      />
    </>
  );
};

export default Parent;

The above code showcases a parent component called Parent that utilizes the TextInputBox component. Here’s a summary of the code:

The Parent component is defined as a functional component. It maintains a state variable called textInputBoxValue using the React.useState hook, initialized with an empty string.

Two event handler functions are defined within the Parent component. The onTextInputBoxChange function updates the textInputBoxValue state variable with the new value passed as an argument. The onTextInputBoxClear function sets the textInputBoxValue state variable back to an empty string.

In the component’s return statement, the TextInputBox component is rendered. It receives props: value, onChange, and onClear. The value prop is set to the textInputBoxValue state variable, while the onChange and onClear props are assigned the respective event handler functions defined in the Parent component.

The Parent component is exported as the default export, making it available for use in other files.

Update App.tsx as below.

import React from "react";
import "./App.css";
import Parent from "./components/Parent";

function App() {
  return (
    <div className="App">
      <h2>React Control props Pattern Example</h2>
      <Parent />
    </div>
  );
}

export default App;

The above code renders a <div> element with the class name “App”. Inside this <div>, a heading with the text “React Control props Pattern Example” is displayed. Additionally, the Parent component is rendered

Once rendered you can see below output.

You can try input some text in textbox and click on clear. All should be working for you if you followed above example correctly. You must be observed that the TextInputBox component is not responsible for managing the state and that is passed by the Parent component or we can say consumer component.

Conclusion

The Control Props pattern in React is a powerful technique that allows a parent component to maintain control over the state of its child components. By passing both the value and event handlers from the parent to the child, the parent component can effectively manage and manipulate the child component’s state.

In this blog post, we explored a simple example that demonstrated the implementation of the Control Props pattern. The example consisted of a parent component, <Parent>, and a child component, <TextInputBox>. The parent component controlled the state of the child component’s input value by passing the value prop and event handlers for input changes and clearing.

By adopting the Control Props pattern, developers can achieve greater control and flexibility in managing the state of their React components. This pattern promotes reusability and encapsulation, allowing components to be easily composed and modified.

Remember, while the example provided was straightforward, the Control Props pattern can be applied to various scenarios and can be adapted to suit specific application requirements. By mastering this pattern, developers can build more robust and maintainable React applications.

Leave a Comment