Author avatar

Gaurav Singhal

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

Gaurav Singhal

  • Sep 15, 2020
  • 6 Min read
  • 17,039 Views
  • Sep 15, 2020
  • 6 Min read
  • 17,039 Views
Web Development
Front End Web Development
Client-side Framework
React

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.

1
2
3
4
5
6
7
8
class ParentComponent extends Component {
    state = {
        // ..
    }
    render() {
        return <ExampleComponent data={this.state}>
    }
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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>
    );
  }
}
jsx

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.

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

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

1
2
3
4
5
// ...
<Button variant="primary" type="button" onClick={() => loginUser(this.state)}>
  Submit
</Button>
// ...
jsx

The complete code for the component file is as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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;
jsx

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.
1
2
3
4
5
6
7
8
9
10
<Button
  variant="primary"
  type="button"
  onClick={() => {
    const { email, password } = this.state;
    loginUser({ email, password });
  }}
>
  Submit
</Button>
jsx
  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.

25