Search code examples
typescriptswitch-statementweb-componentlit-elementlit

A better way to handle input in lit component


I am looking for a better way to handle all inputs in my lit component. I want to use less code. I am also using Typescript. I am using @change=${this.handleInput} for all my inputs. Here is a code how this function looks like:

  handleInput(e: Event) {
    const input = e.target as HTMLInputElement;

    switch(input.id){
      case 'title':
        this.title = input.value 
        break;
      case 'description':
        this.description = input.value 
        break;
        case 'startDate':
          this.startDate = input.value 
          break;
        case 'endDate':
          this.endDate = input.value 
          break;
        case 'startTime':
          this.startTime = input.value 
          break;
        case 'endTime':
          this.endTime = input.value 
          break;
      default:
        return
    }
  } 

This is reactive properties:

@property() title: string 
@property() description: string 
@property() startDate: string
@property() endDate: string
@property() startTime: string
@property() endTime: string

This is a html that renders in the component:

  <form>
        <h2>Add</h2>
        <fieldset>
        <legend>*Information</legend>
          <div class="form-row">
            <label for="courseTitle">*Title</label>
            <input type="text" id="title" name="title" @change=${this.handleInput} required />
          </div>
          <div class="form-row">
            <label>*Description </label>
            <textarea rows="10" cols="50" id="description" @change=${this.handleInput}></textarea>
          </div>
        </fieldset>
        <fieldset>
          <legend>*Date</legend>
            <div class="form-row">
              <label>Start</label>
              <input type="date" id="startDate" name="startDate" @change=${this.handleInput} required />
            </div>
            <div class="form-row">
              <label>End</label>
              <input type="date" id="endDate" name="endDate" @change=${this.handleInput} required />
            </div>
        </fieldset>

        <fieldset>
          <legend>*Time</legend>
          <div class="form-row">
            <label>Start</label>
            <input type="time" id="startTime" name="startTime" @change=${this.handleInput} required />
          </div>
          <div class="form-row">
            <label>End</label>
            <input type="time" id="endTime" name="endTime" @change=${this.handleInput} required />
          </div>
        </fieldset>
        </div>
      </form>

Solution

  • How about switching your switch statement for:

    handleInput( evt ) {
      let { id , value } = evt.target;
      this[ id ] = value;
    }