Issue
I need an input that will have min width and max width and it will grow and shrink according to its content
Solution
You have to have state. It can be passed as a parameter (hoisted state, when a state is at the upper level) or be right in the component
Then just use the length of the input-state
Old solution
const {useState} = React;
const Input = (props) => {
const [value, changeValue] = useState('');
return (
<input
size={Math.min(Math.max(value.length, 2), 20)}
value={value}
onChange={(event) => {changeValue(event.target.value);}}
/>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Input />
);
input {
font-family: "Roboto", monospace;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Old solution
const Input = (props) => {
const [value, changeValue] = React.useState('');
return (
<input
style={{ width: Math.min(Math.max(value.length, 2), 50) + 'ch' }}
value={value}
onChange={(event) => {
changeValue(event.target.value);
}}
/>
);
};
ReactDOM.createRoot(document.getElementById('root')).render(<Input />);
input {
font-family: "Roboto", monospace;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Math.min and Math.Max are used to have size between min(2) and max(20). Without monospace font-family you can get other results
Answered By - FreePhoenix888
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.