score:1

Accepted answer

you need to have state inorder to make the input field (name) controlled.

import react from "react";
import reactdom from "react-dom";

import "./styles.css";

class app extends react.component {
  constructor(props) {
    super(props);
    this.state = { name: "" };
  }

  handleclick = (event) => {
    if (!this.state.name) {
      alert("name should not be empty !");
    }
  };
  changehandler = (event) => {
    this.setstate({ name: event.target.value });
  };

  render() {
    return (
      <div classname="app">
        name :
        <input
          id="name"
          type="text"
          placeholder="name"
          name="aname"
          value={this.state.name}
          onchange={this.changehandler}
        />
        <button classname="btn btn-danger" onclick={this.handleclick}>
          submit
        </button>
      </div>
    );
  }
}

const rootelement = document.getelementbyid("root");
reactdom.render(<app />, rootelement);

score:1

it's quite simple. you need to use a state variable for this.

explanation:

  • i have defined state variable name and used that in textbox
  • on change of input value i am assigning input text inside name variable
  • and then on handleclick, checking whether it's empty or not and based on that showing alert box

working example: codesandbox

solution

 constructor(props) {
    super(props);
    this.state = { 
       name: '' 
    };
  }


  handleclick = () => {    
    if (!this.state.name) {
      alert('please enter');
    }
  };
  render() {
    return (
      <div classname="app">
        name{" "}
        <input
          type="text"
          value={this.state.name}
          onchange={(e) => this.setstate({ name: e.target.value })}
        />
        <button classname="btn btn-danger" onclick={this.handleclick}>
          submit
        </button>
      </div>
    );
  }

Related Query

More Query from same tag