generate react text input in typescript

Here's an example of how to generate a text input in React with TypeScript:

import React, { useState } from 'react';

type InputProps = {
  label: string;
  value: string;
  handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  name: string;
};

const TextInput: React.FC<InputProps> = ({
  label,
  value,
  handleChange,
  placeholder,
  name,
}) => {
  return (
    <div>
      <label htmlFor={name}>{label}</label>
      <input
        type="text"
        value={value}
        onChange={handleChange}
        placeholder={placeholder}
        name={name}
      />
    </div>
  );
};

export default TextInput;
579 chars
33 lines

This component takes in several props:

  • label: the label for the input
  • value: the current value of the input
  • handleChange: a function to be called when the input value changes
  • placeholder: an optional placeholder for the input
  • name: a name for the input (used for labels and form submission)

In the body of the component, we render a label and an input element. The htmlFor attribute of the label matches the name attribute of the input, and the value, onChange, placeholder, and name attributes of the input are set according to the props passed in.

The handleChange function must be of type (event: React.ChangeEvent<HTMLInputElement>) => void, which means it takes in a change event and returns nothing. This function should be responsible for updating the value of the input in the parent component's state or props, depending on your application's architecture.

gistlibby LogSnag