Home > Software design >  Resetting dropdown box to original value in react
Resetting dropdown box to original value in react

Time:11-10

Hello I am working in react and am fairly new to it, I am working to reset the field values to its original state after a user has submitted an athlete (after clicking the create record button) and I want the dropdown text box to return to "Other" if a user has changed the field to something else. So for example. First Name: "John", Last Name: "Smith", Sport: "Men's Golf" would reset to

First Name: "", Last Name: "", Sport: "Other" I've managed to reset all the other fields but the sport dropdown field isn't resetting and I have no clue why. Here is the code I'm working with.

import React from "react";
import "./athleteEntryStyle.css";
import { baseUrl } from "../../serviceConfig";

interface Props {
  username?: string;
  password?: string;
  dominant_foot?: string;
  preferred_name?: string;
  position?: string;
  firstName: string;
  middleName: string;
  lastName: string;
  phone: string;
  email: string;
  dateOfBirth: string;
  sport: string;
}

interface State {
  username?: string;
  password?: string;
  dominant_foot?: string;
  preferred_name?: string;
  position?: string;
  firstName: string;
  middleName: string;
  lastName: string;
  phone: string;
  email: string;
  dateOfBirth: string;
  sport: string;
}

export class AthleteEntry extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      username: props.username,
      password: props.password,
      dominant_foot: props.dominant_foot,
      preferred_name: props.preferred_name,
      position: props.position,
      firstName: props.firstName,
      middleName: props.middleName,
      lastName: props.lastName,
      phone: props.phone,
      email: props.email,
      dateOfBirth: props.dateOfBirth,
      sport: props.sport,
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event: { target: any }) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    console.log(target);
    console.log(value);
    console.log(name);
    const newState = { [name]: value } as Pick<Props, keyof State>;
    this.setState(newState);
    
  }

  handleSubmit(event: { preventDefault: () => void }) {
    const request = JSON.stringify({
      username: this.state.username,
      email: this.state.email,
      password: this.state.password,
      first_name: this.state.firstName,
      middle_name: this.state.middleName,
      last_name: this.state.lastName,
      phone_number: this.state.phone?.toString(),
      dominant_foot: this.state.dominant_foot,
      sport: this.state.sport,
      position: this.state.position,
      preferred_name: this.state.preferred_name,
      date_of_birth: new Date(this.state.dateOfBirth).toISOString(),
    });

    console.log("Request from app");
    console.log(request);

    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: request,
    };
    this.setState({firstName: "", middleName: "", lastName: "", preferred_name: "", dateOfBirth: "date", phone: "", email: "", 
    username: "", password: "", dominant_foot: "", sport: "Other", position: "" });
    //NOTE: This is assuming your service instance is running locally, we have to either make a config file that allows you to switch this as necessary or
    //switch this to the hosted service when that becomes a thing
    fetch(baseUrl   "athlete/create", requestOptions).then(function (response) {
      if (response.status == 201) {
        alert("An athlete was successfully created.");
      } else {
        alert(
          "Error creating athlete: API responded with code "  
            response.status.toString()
        );
      }
    });
    event.preventDefault();

  }

  render() {
    return (
      <form
        className="form"
        onSubmit={this.handleSubmit}
        style={{
          display: "flex",
          padding: "20px",
          height: "100vh",
          background: "linear-gradient(#fff, #d00000)",
        }}
      >
        <div>
          <div style={styles}>
            <label className="label">First Name:</label>
            <input
              name="firstName"
              className="input"
              type="text"
              value={this.state.firstName}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Middle Name:</label>
            <input
              name="middleName"
              className="input"
              type="text"
              value={this.state.middleName}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Last Name:</label>
            <input
              name="lastName"
              className="input"
              type="text"
              value={this.state.lastName}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Preferred Name:</label>
            <input
              name="preferred_name"
              className="input"
              type="text"
              value={this.state.preferred_name}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Date of Birth:</label>
            <input
              name="dateOfBirth"
              className="input"
              type="date"
              value={this.state.dateOfBirth}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Phone Number:</label>
            <input
              name="phone"
              className="input"
              type="text"
              value={this.state.phone}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Email:</label>
            <input
              name="email"
              className="input"
              type="text"
              value={this.state.email}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Username:</label>
            <input
              name="username"
              className="input"
              type="text"
              value={this.state.username}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Password:</label>
            <input
              name="password"
              className="input"
              type="password"
              value={this.state.password}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Dominant Foot:</label>
            <input
              name="dominant_foot"
              className="input"
              type="text"
              value={this.state.dominant_foot}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Sport:</label>
            {/* <input
              name="sport"
              className="input"
              type="text"
              value={this.state.sport}
              onChange={this.handleChange}
            /> */}
            <select
              name="sport"
              className="input"
              id="sport"
              defaultValue="Other"
              onChange={this.handleChange}
            >
              <option value="Football (MFB)">Football (MFB)</option>
              <option value="Baseball (MBA)">Baseball (MBA)</option>
              <option value="Softball (WSB)">Softball (WSB)</option>
              <option value="Men's Basketball (MBB)">
                Men's Basketball (MBB)
              </option>
              <option value="Women's Basketball (WBB)">
                Women's Basketball (WBB)
              </option>
              <option value="Men's Cross Country (MCC)">
                Men's Cross Country (MCC)
              </option>
              <option value="Women's Cross Country (WCC)">
                Women's Cross Country (WCC)
              </option>
              <option value="Men's Golf (MGO)">Men's Golf (MGO)</option>
              <option value="Women's Golf (WGO)">Women's Golf (WGO)</option>
              <option value="Women's Soccer (WSO)">Women's Soccer (WSO)</option>
              <option value="Women's Volleyball (WVB)">
                Women's Volleyball (WVB)
              </option>
              <option value="Women’s Bowling (WBW)">
                Women’s Bowling (WBW)
              </option>
              <option value="Men’s Gymnastics (MGY)">
                Men’s Gymnastics (MGY)
              </option>
              <option value="Women’s Gymnastics (WGY)">
                Women’s Gymnastics (WGY)
              </option>
              <option value="Women’s Swimming/Diving (WSW)">
                Women’s Swimming/Diving (WSW)
              </option>
              <option value="Men’s Tennis (MTE)">Men’s Tennis (MTE)</option>
              <option value="Women’s Tennis (WTE)">Women’s Tennis (WTE)</option>
              <option value="Men’s Wrestling (MWR)">
                Men’s Wrestling (MWR)
              </option>
              <option value="Women’s Rifle (WRI)">Women’s Rifle (WRI)</option>
              <option value="Women’s Track (WTO)">Women’s Track (WTO)</option>
              <option value="Men’s Track (MTO)">Men’s Track (MTO)</option>
              <option value="Other">Other</option>
            </select>
          </div>
          <div style={styles}>
            <label className="label">Position:</label>
            <input
              name="position"
              className="input"
              type="text"
              value={this.state.position}
              onChange={this.handleChange}
            />
          </div>
          <div style={{ marginBottom: 12, padding: 10 }}>
            <label>
              <input type="submit" value="Create Record" className="button"/>
            </label>
          </div>
        </div>
      </form>
    );
  }
}
const styles = {
  marginBottom: 12,
};

Most of the code above won't matter to you except the line where the change is made. So

this.setState({firstName: "", middleName: "", lastName: "", preferred_name: "", dateOfBirth: "date", phone: "", email: "", 
    username: "", password: "", dominant_foot: "", sport: "Other", position: "" });

is where the change is being made.

CodePudding user response:

Looks like you have defaultValue="Other" as a prop in your select component, but what you really want is value={this.state.sport}, like you have in the commented out input above it. This will make it a controlled component, so the value of that select field will be based on your state. The other fields are done that way, looks like it may have just been an oversight.

  • Related