Home > front end >  Id selection of a specific Textfield in react
Id selection of a specific Textfield in react

Time:03-25

I have a component with different Textfields and would like to access specific IDs, for example the textfield that has the label='Elevator amount'. I'm trying something like this but I'm not sure how to properly select the id.

let elevatorAmt = (document.getElementById('ID I want to select') as HTMLInputElement);

these are the Textfields in my component

interface Props{
num: number | undefined;
setNum: React.Dispatch<React.SetStateAction<number | undefined>>;
handleAdd: (e: React.FormEvent) => void;
}

const Results = ({ num, setNum, handleAdd }: Props) => {
const inputRef = useRef<HTMLInputElement>(null);

return ( 
    <Grid>
        <form className='input' onSubmit={(e) => {
            handleAdd(e)
            inputRef.current?.blur();
        }}>

            <TextField
                id="outlined-read-only-input"
                label="Elevator amount"
                color='primary'
                variant="outlined"
                type="number"
                InputLabelProps={{
                  shrink: true,
                }}
                InputProps={{
                  readOnly: true,
                }} />
            <TextField
                id="outlined-read-only-input"
                label="Unit Price of Elevators"
                color='primary'
                variant="outlined"
                type="number"
                InputLabelProps={{
                  shrink: true,
                }}
                InputProps={{
                  readOnly: true,
                }} />

I pass my component like so:

<Results num={num} setNum={setNum} handleAdd={handleAdd} />

thanks for your help

EDIT: I mentioned Id but I want access the value, it doesn't matter how

CodePudding user response:

As you said in the comment, you actually want the value of the textfield. In this case you need to set a state for your textfield component and update that state whenever the value of the textfield is changed. It would be something like this:


const MyComponent = () => {

    const [text, setText] = useState();

    return 
       <div>
           <TextField
            id="outlined-read-only-input"
            label="Elevator amount"
            color='primary'
            variant="outlined"
            type="number"
            InputLabelProps={{
              shrink: true,
            }}
            InputProps={{
              readOnly: true,
            }}
            //This will update the state whenever it's value changes.
            onChange={(event) => {setText(event.target.value)}} 
           />
      </div>

}

By doing that, text will always contain the current value of what is in the text field.

By the way, I'm assuming you're using material-ui. The component and it's props looks like it.

  • Related