Passing specific attributes to a component in React

Asked

Viewed 43 times

-2

Hello, I have a question about how to use attributes in a component created in React. Imagine that I created the following component:

const AnimatedInput = ({ label, type }) => {
    return (
        <div className='animatedInput'>
            <input  name={label} className='animatedInput__input' type={type} required />
            <span className='animatedInput__span'>{label}</span>
        </div>
    )
}

Now when I use this component elsewhere in my application I call it normally:

<AnimatedInput label={'Nome'} type={'text'}/>

My question is, and if I want to pass proper attributes of input(for example) within this tag, it has how to do this ?

I know that in Typescript we can extend these attributes, but in this case I am not using Typescript.

Thanks for your help.

2 answers

0

From what I can understand, you want to use a past attribute as props of your component within the Component input, if that is so, you can use it as a reference, for example:

<AnimatedInput label={'Nome'} type={'text'} value={valorInput}/>

And inside the Component use it in the same way as in the example. Receiving by parameter and using inside the input.

Does that answer your question or did I miss her right?

  • Thanks for the answer

0

You can use the spread as well (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)

See an example here: https://codesandbox.io/s/teste-spread-np3xb?file=/src/App.js

import React from "react";
import "./styles.css";

//seu input customizado
function MyInput({ title, ...rest }) {
  return (
    <>
      <label>{title}</label>
      <input {...rest} />
    </>
  );
}

export default function App() {
  return (
    <div className="App">
      <MyInput
        title="Teste"
        name="Teste"
        type="text"
        placeHolder="Testando..."
      />
    </div>
  );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.