Dynamically update the input width based on the input value length
npm install @jimsheen/react-dynamic-input-widthDynamically update the input width based on the input value length
   
```
npm install @jimsheen/react-dynamic-input-width
Basic example
`
import React from 'react';
import Input from '@jimsheen/react-dynamic-input-width';
export default function InputExample() {
const handleChange = (e: React.ChangeEvent
console.log(e.target.value);
}
const handleKeyPress = (e: React.KeyboardEvent
console.log(e.key);
}
return (
initialValue="Hello there"
padding={10}
initialWidth={100}
onChange={(e) => handleChange(e)}
onKeyPress={(e) => handleKeyPress(e)}
/>
)
}
`
Full example using refs:
`
import React, { useEffect } from "react";
import Input from "@jimsheen/react-dynamic-input-width";
export default function InputExample() {
const [isEdit, setIsEdit] = React.useState(false);
const [value, setValue] = React.useState("Hello there");
// create a ref for the value span
const valueRef = React.useRef
// create a ref for the input
const inputRef = React.useRef
// update value when input is changed
const handleChange = (e: React.ChangeEvent
const { value } = e.target;
setValue(value);
};
// example of handling "Enter" key press
const handleKeyPress = (e: React.KeyboardEvent
if ((e && e.key === "Enter") || !e) {
setIsEdit(!isEdit);
}
};
// toggle the input visibility
const handleClick = () => {
setIsEdit(!isEdit);
};
// focus the input when isEdit is true
useEffect(() => {
if (isEdit) inputRef.current?.focus();
}, [isEdit]);
return (
<>
{!isEdit && {value}}
{isEdit && (
initialValue={value}
padding={0}
// set initialWidth to the width of the value span element
initialWidth={valueRef.current?.offsetWidth}
onChange={(e) => handleChange(e)}
onKeyPress={(e) => handleKeyPress(e)}
ref={inputRef}
/>
)}
>
);
}
`
Input accepts a ref by utilising the forwardRef HOC under the hood
`
const inputRef = React.useRef
ref={inputRef}
/>
`
It's also possible to pass additional props to the underlying input component such as "placeholder" for example
``
placeholder="Placeholder text"
/>
| Prop | Type | Default | Required | Description |
|-------------- |-------- |--------------------- |---------- |----------------------------------------------------------------- |
| initialValue | string | undefined | false | The input's initial value |
| initialWidth | number | undefined | false | The input's initial width value in px |
| padding | number | 1 | false | Add's extra width to the input |
| fontSize | string | 16px | false | The font size of the input (used for measuring the offsetWidth) |
| className | string | input-dynamic-width | false | Default className |
```
initialValue?: string
initialWidth?: number
padding?: number
fontSize?: string
onChange?: (event: React.ChangeEvent
onKeyPress?: (event: React.KeyboardEvent
className?: string