Chandan
Chandan

Reputation: 25

How to show suggestions while entering values in input field?

I'm doing a small react project, working on API calls newly. My objective is, I want to show suggestions below the input field. i mean if we enter name in input field the suggestion should show Name should not exceed 15 characters and once i enter the value the suggestion should get disappear. Can anyone please help me in this query?

Here is my code:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "",
      isName: true,
      error: ""
    };
  }

  ValidName = () => {
    const regex = new RegExp("([a-zA-Z])+$");
    this.setState({
      isName: regex.test(this.state.name)
    });
  };

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

  hSave = event => {
    event.preventDefault();
    const data = { name: this.state.name };
    axios
      .post(`/api/Addcontact`, data, {
        headers: { "Content-Type": "application/json" }
      })
      .then(res => {
        if (res.status == 200) {
          this.props.history.push("/Contact");
        } else {
          this.setState({ error: res });
          console.log(res);
        }
      });
  };
  render() {
    return (
      <div>
        <Form size="large">
          <Segment stacked>
            <Label className="contactLabel">*Name</Label>
            <Form.Input
              fluid
              className={`${this.state.isName ? "" : "error"} saveContact`}
              placeholder="Full Name"
              name="name"
              onChange={this.handleChange}
              onBlur={this.ValidName}
              value={this.state.name}
            />
            {this.state.isName ? (
              ""
            ) : (
              <div className="contactError">* Invalid Name</div>
            )}

{error ? <div>{error}</div> : ""}

            <Button
              color="teal"
              className="saveContactbtn"
              onClick={this.hSave}
            >
              Save
            </Button>
          </Segment>
        </Form>
      </div>
    );
  }
}
export default App;

I'm unable to figure it out, how to show the suggestion for the input field!

Upvotes: 0

Views: 1472

Answers (2)

Oshini
Oshini

Reputation: 633

Try this code. hope it will help you. but it's manual validation.

import React, { Component } from 'react'

class AddUser extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userName: "",
      errors: {},
    };
    this.handleUsername = this.handleUsername.bind();
    this.handleAddUser = this.handleAddUser.bind();
  }

   //UserName change event
  handleUsername(event) {
    let userName = event.target.value;
    let errors = {};
    let lastAt = userName.lastIndexOf('@');
    let lastDot = userName.lastIndexOf('.');

    if (!(lastAt < lastDot && lastAt > 0 && userName.indexOf('@@') === -1 && lastDot > 2 && (userName.length - lastDot) > 2)) {
      errors["username"] = "Your email is required and it should be valid ";
    }

    this.setState({
      userName: event.target.value,
      errors: errors,
    });
  }

  //ADD user button on click
  handleAddUser = () => {
    let formIsValid = true;
   //TODO :formIsValid needs to false when you have validation errors

    if (formIsValid) {
      //TODO :API call for submit 
    }
  };


  render() {
    return (
      <div className="user-sidebar sidebar-nav has-header">
        <form name="addUserForm">
          <div className="form-group">
            <div className="col-sm-4">
              <label className="control-label" htmlFor="username">User Name: </label>
            </div>
            <div className="col-sm-8">
              <input className="form-control" name="username" placeholder="Username" autoFocus required value={this.state.userName} onChange={this.handleUsername} />
              <span className="error-message">{this.state.errors["username"]}</span>
            </div>
          </div>

          <div className="form-group">
             <button type="button" className="btn btn-primary" onClick={() => { this.handleAddUser(this) }}><i className="fa fa-plus"></i> Add User</button>
          </div>
        </form>

      </div>
    )
  }
}

Upvotes: 1

keikai
keikai

Reputation: 15166

Description

You need a validation service/lib to implement your demand of:
1.show info related to the user input value
2.once input meets the condition, make it disappear (font / other css styles)

Implement

optional validation lib: react-hook-form

sample:

Edit React Hook Form - Get Started

Upvotes: 2

Related Questions