Pass data from parent to child component in React JS

When developing ReactJS we tend to develop small, isolated, reuseable component and we can achieve it by building smart and dump component (or you can call parent-child component).

Basically:

  • Smart component will be Class component contain all state of that component with event handler, ajax call, modify state etc…
  • Dump component will be plain html like button, input.

Today, I will build small demo to handle event occur in child component and parent component will process that event.

I will define my child component like this

import React from "react";
import PropTypes from "prop-types";

const ACCInput = props => {
  const className = "form-control";
  const classNameError = "form-control is-invalid";

  return (
    <div className="form-group">
      <label htmlFor={props.name} hidden>
        {props.name}
      </label>
      <div>
        <input
          className={props.className ? classNameError : className}
          id={props.id}
          type={props.type}
          name={props.name}
          placeholder={props.placeholder}
          onFocus={props.onFocus}
          onChange={props.onChange}
          onBlur={props.onBlur}
          value={props.value}
          required={props.required}
          disabled={props.disabled}
        />
      </div>
    </div>
  );
};


ACCInput.propTypes = {
  className: PropTypes.bool,
  id: PropTypes.string,
  type: PropTypes.string,
  name: PropTypes.string,
  placeholder: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func,
  onBlur: PropTypes.func,
  onFocus: PropTypes.func,
  required: PropTypes.string,
  disabled: PropTypes.string
};

export default ACCInput;

We only need to focus at onChange={props.onChange} line. The props.onChange mean the child component will call function from parent component. The value={props.value} mean I will update value everytime user type something.

Next in my smart component I will call the custom input I just created in render

<ACCInput
className={shouldMarkError.call(this, "username", errors)}
type="text"
name="username"
id="username"
placeholder="Username"
required="required"
value={username}
onChange={this.onChange}/>

Next in the onChange

onChange(e) {
  this.setState({ [e.target.name]: e.target.value });
}

So everytime user type something the state of username will be update and will be paste to child component

Full source code can be found at

ACCInput

LoginForm

So that is. Happy coding!!!

Leave a comment