Change value when user input value

Viewed 51

I have collected the code used to convert units in CSS When the user changes the value in the input, the inputs also change. How does the below code work? in function NumberInput where did I go wrong, please show me! I'm a newbie to react :D

Code that executes on codesandbox.

import React from 'react'
import { ListType } from './types'

export default function CssUnits() {
  const [em, setEm] = React.useState<number>(1)
  ...

  const emHandler = (val: number) => {
    setRem(val)
    setPx(val * 16)
    setPercent(val * 100)
    setPt(val * 12)
  }
  ...

  const List: ListType[] = [
    {
      label: 'EM',
      description: 'Relative to the font-size of the element',
      state: em,
      onChange: (val) => {
        emHandler(val || 0)
      },
    },
    ...
  ]

  function NumberInput({ key, value, variant, label, description, onChange, precision }) {
    return (
        <div key={key} className="my-8">
            <div className="text-xl font-medium">{label} <span className="text-sm text-gray-400">({description})</span></div>
            <input type='text' value={value} onChange={onChange}/>
        </div>
    );
  }
  
  return (
    <div className="my-4">
      <h2>CSS Units converter</h2>
        {List.map((item, index) => {
          const decimalPoint = item.state.toString().split('.')
          return (
            <NumberInput
              key={index}
              value={item.state}
              variant='default'
              label={item.label}
              description={item.description}
              onChange={item.onChange}
              precision={decimalPoint[1] ? decimalPoint[1].length : 0}
            />
          )
        })}
    </div>
  )
}
1 Answers

onChange function in NumberInput pass event to the item.onChange. So, you need to change this part of your code:

 onChange={item.onChange}

to:

onChange={(e) => item.onChange(e.target.value)}

for passing correct value!

Also, in every handler you should set current handler value to see current input value changes simultaneously.

You can refer to this codesandbox:

Edit pensive-shape-rpdxwq

Related