Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Send State of Current Component as a Parameter to Another External Method Using React

Sep 15, 2020 • 7 Minute Read

Introduction Communicating data between React components is crucial as it allows you to create more dynamic web applications. But since React has only one-way data flow, it can get tricky to communicate or send data to other components.

To update the state in a parent component, you have to pass the data into the callback prop. Instead of giving the data or state into the callback prop, you can send it directly to an external method to complete a specific task. In this guide, you'll learn how to submit a component's state to an external method.

State in React

In React, the state of the component is an object that contains some data. The state may change over the lifecycle of the component. Earlier, states were only used in class-based components, but now because of hooks, you can use the useState hook to leverage state in a function-based component.

Passing State to a Component

Before diving into how to send state to an external method, take a look at how to pass it to a component.

To pass the state into another component, you can pass it as a prop.

      class ParentComponent extends Component {
    state = {
        // ..
    }
    render() {
        return <ExampleComponent data={this.state}>
    }
}
    

Then, inside <ExampleComponent />, you can access the data as this.props.data.

Passing State to an External Method

Sending state to an external method is similar to passing state to a child component. Passing this.state into the external method's parameter will do the trick.

Let's take an example of a login form from the React Bootstrap documentation. It will have the email and password in its state.

      class LoginForm extends Component {
  state = {
    email: "",
    password: ""
  };

  handleChange = e => this.setState({ [e.target.name]: e.target.value });

  render() {
    return (
      <Form>
        <h2>Login</h2>
        <hr />
        <Form.Group controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            placeholder="Enter email"
            onChange={this.handleChange}
          />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
          </Form.Text>
        </Form.Group>

        <Form.Group controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            placeholder="Password"
            onChange={this.handleChange}
          />
        </Form.Group>
        <Form.Group controlId="formBasicCheckbox">
          <Form.Check type="checkbox" label="Check me out" />
        </Form.Group>
        <Button variant="primary" type="button">
          Submit
        </Button>
      </Form>
    );
  }
}
    

Pass the state of the <LoginForm /> component to a loginUser() external method, which will handle the network request to check whether the email and password are correct.

The loginUser() method is shown below.

      const loginUser = async values => {
  const res = await fetch({ url: SERVER_URL, method: "POST", body: values });
  const data = await res.json();
  return data;
};
    

Now, call the loginUser() method inside the onClick handler of the <Button /> component inside the form.

      // ...
<Button variant="primary" type="button" onClick={() => loginUser(this.state)}>
  Submit
</Button>
// ...
    

The complete code for the component file is as follows.

      import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";

const loginUser = async values => {
  const res = await fetch({ url: SERVER_URL, method: "POST", body: values });
  const data = await res.json();
  return data;
};

class LoginForm extends Component {
  state = {
    email: "",
    password: ""
  };

  handleChange = e => this.setState({ [e.target.name]: e.target.value });

  render() {
    return (
      <Form>
        <h2>Login</h2>
        <hr />
        <Form.Group controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            placeholder="Enter email"
            onChange={this.handleChange}
          />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
          </Form.Text>
        </Form.Group>

        <Form.Group controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            placeholder="Password"
            onChange={this.handleChange}
          />
        </Form.Group>
        <Form.Group controlId="formBasicCheckbox">
          <Form.Check type="checkbox" label="Check me out" />
        </Form.Group>
        <Button
          variant="primary"
          type="button"
          onClick={() => loginUser(this.state)}
        >
          Submit
        </Button>
      </Form>
    );
  }
}

export default LoginForm;
    

There are two things to note here:

  1. It's best to pass the state keys explicitly inside the onClick handler rather than sending the whole state. You may end up giving the internal state to the method as you make future changes.
      <Button
  variant="primary"
  type="button"
  onClick={() => {
    const { email, password } = this.state;
    loginUser({ email, password });
  }}
>
  Submit
</Button>
    
  1. You can only pass the whole state in a class-based component. Functional components have individual state variables that are created by the useState hook.

Conclusion

Now you understand the concept of state and how to pass state as props to other components or as a parameter to an external method. The key thing to remember is that it's always a best practice to explicitly pass individual state values instead of a whole state object.

Learn More

Explore these React courses from Pluralsight to continue learning today: