Author avatar

Kimaru Thagana

Manually Set Up Input Values in React.js

Kimaru Thagana

  • Oct 17, 2020
  • 9 Min read
  • 30 Views
  • Oct 17, 2020
  • 9 Min read
  • 30 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

During design and development of frontend interfaces in React.js, you will come across instances where you require user data. Working with user data is an essential skill for any React developer. Some scenarios require you to manually set input data before sending it to an API or a database.

Consider a scenario where you, as a React developer, are designing a login form that requires a user to input their username and password. Before the user is logged into your application, your React app needs to display a captcha code that the user submits to verify that they aren't a robot. This guide will show you how to manually generate and set up this captcha input.

Set Up Sample App

Open your terminal and run these commands to create a basic React app.

1
2
3
4
5
npx create-react-app react-manually_setInput

cd react-manually_setInput

npm start
bash

Include React Bootstrap in your basic React app.

1
npm install react-bootstrap bootstrap
bash

In your app.js file, include the stylesheet as well.

1
import 'bootstrap/dist/css/bootstrap.min.css';
js

Initial Setup

Copy and paste the sample code below to create a simple login form with a username, password, and captcha inputs that you will manually generate.

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import React, {Component} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button, Row, Col, Card, Form} from 'react-bootstrap';


class App extends Component{
  constructor(props) {
    super(props);
    this.state = ({
        display: false,
        btnDisplay: false,
        username: "",
        password: "",
    });

    this.handleUsername = this.handleUsername.bind(this);
    this.handlePassword = this.handlePassword.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }
  handleUsername(e){
      let username = e.target.value;
      this.setState({
          username: username
      })
  }

  handlePassword(e){
      let password = e.target.value;
      this.setState({
          password: password
      })
  }

  handleSubmit(e) {
      e.preventDefault();
      if (!this.state.username && !this.state.password)
          return;
      this.setState({
          display: true,
          btnDisplay:true
      })
  }

  renderCaptcha(){
      return(
          <div>
              <Form.Group as={Row} controlId="formPlaintextEmail">
                  <Form.Label column sm="4">
                      Captcha
                  </Form.Label>
                  <Col>
                      <Form.Control type="text" placeholder="Enter Captcha"  />
                  </Col>
              </Form.Group>

              <Button variant="primary" type="save" disabled={this.state.btnDisplay}>
                  Login
              </Button>

          </div>
      )
  }

  render() {
    return (
        <Row>
          <Col>
            <Card style={{ width: '20rem' }}>
                <Card.Body>
                    <Form>
                        <Form.Group >
                            <Form.Label>Username</Form.Label>
                            <Form.Control type="username" placeholder="Enter username"
                                          onChange={this.handleUsername}
                            />
                        </Form.Group>

                        <Form.Group >
                            <Form.Label>Password</Form.Label>
                            <Form.Control type="password" placeholder="Password"
                                          onChange={this.handlePassword}
                            />
                        </Form.Group>

                        <Button variant="primary" type="submit"
                                onClick={this.handleSubmit}
                        >
                            Submit
                        </Button>

                        {this.state.display? this.renderCaptcha():""}
                    </Form>

                </Card.Body>
            </Card>
          </Col>
        </Row>
    );
  }
}

export default App;
js

In the sample code above, the captcha form will not be visible at first. The handleSubmit function verifies that there are no null values and proceeds to set the display to true. This then triggers your captcha form to be visible and forces the user to enter captcha values that will be manually generated and displayed. The code also ensures that the user can't log in without the captcha by disabling the login button.

Once that's done, the next step is to create captcha values at random, then display them to the user. Copy the sample code below.

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import React, {Component} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button, Row, Col, Card, Form} from 'react-bootstrap';


class App extends Component{
  constructor(props) {
    super(props);
    this.state = ({
        display: false,
        btnDisplay: false,
        username: "",
        password: "",
        captcha: "",
        userCaptcha: ""
    });

    this.handleUsername = this.handleUsername.bind(this);
    this.handlePassword = this.handlePassword.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleCaptcha = this.handleCaptcha.bind(this);

  }
  handleUsername(e){
      let username = e.target.value;
      this.setState({
          username: username
      })
  }

  handlePassword(e){
      let password = e.target.value;
      this.setState({
          password: password
      })
  }

  handleSubmit(e) {
      e.preventDefault();
      if (!this.state.username && !this.state.password)
          return;
      this.setState({
          display: true,
          btnDisplay:true
      });

      let random = Math.random().toString(36).substring(7);
      this.setState({
          captcha: random
      })

  }
    handleCaptcha(e){
      let userCaptcha = e.target.value
      if(!userCaptcha)
          return;
      this.setState({
          btnDisplay: false
      })

    }


  renderCaptcha(){
      return(
          <div>
              <Form.Group as={Row} controlId="formPlaintextEmail">
                  <Form.Label column sm="4">
                      {this.state.captcha}
                  </Form.Label>
                  <Col>
                      <Form.Control type="text" placeholder="Enter Captcha" onChange={this.handleCaptcha} />
                  </Col>
              </Form.Group>

              <Button variant="primary" type="save" disabled={this.state.btnDisplay} >
                  Login
              </Button>

          </div>
      )
  }

  render() {
    return (
        <Row>
          <Col>
            <Card style={{ width: '20rem' }}>
                <Card.Body>
                    <Form>
                        <Form.Group >
                            <Form.Label>Username</Form.Label>
                            <Form.Control type="username" placeholder="Enter username"
                                          onChange={this.handleUsername}
                            />
                        </Form.Group>

                        <Form.Group >
                            <Form.Label>Password</Form.Label>
                            <Form.Control type="password" placeholder="Password"
                                          onChange={this.handlePassword}
                            />
                        </Form.Group>

                        <Button variant="primary" type="submit"
                                onClick={this.handleSubmit}
                        >
                            Submit
                        </Button>

                        {this.state.display? this.renderCaptcha():""}
                    </Form>

                </Card.Body>
            </Card>
          </Col>
        </Row>
    );
  }
}

export default App;
js

In the sample code above, you have declared handleSubmit and handleCaptcha. Inside the handleSubmit function, there's a random code generator for the captcha. This sets the captcha state and subsequently updates the captcha input label with the random code.

The handleCaptcha function checks if there're any values in the captcha text input and enables the login button.

So far, you have learned how to create and set input values manually. Let's finish up by ensuring the captcha values the user enters correspond to the values given.

Add a handleLogin function, which will verify the values generated, and the user input.

1
2
3
4
5
6
7
8
9
  handleLogin()
    {
      if(this.state.userCaptcha === this.state.captcha){
          alert("correct captcha")
      }
      else{
          alert("incorrect captcha!!")
      }
    }
js

Conclusion

Manually setting input values in React.js gives you the ability to manipulate input forms and further design an app as you wish. This skill is mostly used by React and frontend developers who design and develop user interfaces.

Build on this guide by learning how to create form inputs on the official React.js site.

0