Oct 08, 2022
How to handle multiple Same inputs box in React for Bulk Data Insert With Use of useRef Hook?How to get Custom attributes value in React With Use of useRef Hook ?NaN
#react#programming#useRef()#beginners
How to Change Input Box defaultValue In React Js using useRef() Hook ? In this Post, we will learn about how to handle multiple input Box defaultValue using useRef() React Hook.
1)onInputChange() Function
const onInputChange = (e) => {
ref.current[parseInt(e.currentTarget.attributes['refindex'].value)].value =e.target.value;
}How to get All Input Box Value and Store in Array ?
2)ShowValue() Function
const ShowValue = () => {
const myInputValue = [];
for (let i = 0; i < ref.current.length; i++) {
myInputValue.push({
[ref.current[i].name]: ref.current[i].value
})
}
console.log(myInputValue);
}How to Clear All Input Box Value ?
3)ClearValue() Function
const ClearValue = () => {
for (let i = 0; i < ref.current.length; i++) {
ref.current[i].value = 0;
}
}Finally We Completed our Requirement
4)App.js
import './App.css';
import React, { useRef } from 'react';
function App() {
const ref = useRef([]);
const onInputChange = (e) => {
ref.current[parseInt(e.currentTarget.attributes['refindex'].value)].value =e.target.value;
}
const ShowValue = () => {
const myInputValue = [];
for (let i = 0; i < ref.current.length; i++) {
myInputValue.push({
[ref.current[i].name]: ref.current[i].value
})
}
console.log(myInputValue);
}
const ClearValue = () => {
for (let i = 0; i < ref.current.length; i++) {
ref.current[i].value = 0;
}
}
return (
<>
<div style={{ width: '50%', backgroundColor: '#f7f4f3', marginLeft: '150px', marginTop: '100px', padding: '50px 0px 100px 50px' }}>
<label><b>Money</b></label> <input ref={(element) => { ref.current[0] = element }} refindex={0} name='ModeyValue' defaultValue='123464' type='text' onChange={onInputChange} /> <br />
<label><b>Money</b></label> <input ref={(element) => { ref.current[1] = element }} refindex={1} name='ModeyValue' defaultValue='123' type='text' onChange={onInputChange} /> <br />
<label><b>Money</b></label> <input ref={(element) => { ref.current[2] = element }} refindex={2} name='ModeyValue' defaultValue='1' type='text' onChange={onInputChange} /> <br />
<label><b>Money</b></label> <input ref={(element) => { ref.current[3] = element }} refindex={3} name='ModeyValue' defaultValue='1234' type='text' onChange={onInputChange} /> <br />
<button style={{ padding: '5px', backgroundColor: 'green', border: 'none', margin: '5px 5px 5px 5px' }} onClick={ShowValue}>Check All Input Value in Form of Array</button>
<button style={{ padding: '5px', backgroundColor: 'red', border: 'none', margin: '5px 5px 5px 5px' }} onClick={ClearValue}>Clear all Input Value</button>
</div>
</>
);
}
export default App;Well done! Finally We Store All InputBox Value in Array!! Drop some love by liking or commenting ♥
Add a comment
Questions and corrections are both welcome. Your email is not asked for and not stored.