Home > Back-end >  How to send a text parameter to a component
How to send a text parameter to a component

Time:07-13

I'm trying to create a component for Input and I'll need to add an additional parameter in the function to receive a text that will be used on my label (as demonstrated below), however I'm not sure if I'm doing it correctly and I don’t know how to call this.

Component Code:

import './InputAnimation.scss'

import { InputHTMLAttributes } from 'react';

type InputProps = InputHTMLAttributes<HTMLInputElement>; 

export function InputAnimation(props: InputProps, label: string){

    return(
        <div className="form">
            <input id="input" className="form__input form-control" {...props}/>
            <label htmlFor="input" className="form__label">{label}</label>
        </div>
    )
}

And the thing is, how do I call it?

<InputAnimation 
  type={"password"} 
  placeholder={" "}
  onChange={event => setPassword(event.target.value)}
  value={password}
  />

CodePudding user response:

Extend your InputProps type and you can pass label props to InputAnimation

type InputProps = InputHTMLAttributes<HTMLInputElement> & { label: string };

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <InputAnimation
        type={"password"}
        placeholder={" "}
        onChange={(event) => {}}
        value={"password"}
        label="Label"
      />
    </div>
  );
}

const InputAnimation = (props: InputProps) => {
  return (
    <div className="form">
      <input id="input" className="form__input form-control" {...props} />
      <label htmlFor="input" className="form__label">
        {props.label}
      </label>
    </div>
  );
};

CodePudding user response:

the props should be a single object, so please extends your type of props to also receive the label,

type InputProps = InputHTMLAttributes<HTMLInputElement> & {
  label: string;
};

export function InputAnimation(props: InputProps){

    return(
        <div className="form">
            <input id="input" className="form__input form-control" {...props}/>
            <label htmlFor="input" className="form__label">{props.label}</label>
        </div>
    )
}

  • Related