Here, I have an array of objects fabbutton
, and I pass the handlePress
function into the array of objects and call it!.
Step 1. Enter some text in the text input that’s storing the input value inputValue
state.
Step 2. When I clicked the Click me
button at that time, I received the inputValue
state value as null.
How can I fix this issue?
import React, { useEffect, useState } from 'react';
function App() {
const [fabbutton, setFabbutton] = useState([])
const [inputValue, setInputValue] = useState("");
const handlePress = () => {
console.log(inputValue, "inputValue====>>>>"); // Every time return null
}
useEffect(() => {
let arr = [{
label: 'Click me',
onClick: () => handlePress(), // Here i pass the function
}]
setFabbutton(arr);
return () => {
setFabbutton([]);
}
}, [])
return (
<div className="App" style={{ display: 'flex' }}>
<div>
<p>{inputValue}</p>
<input onChange={(e) => setInputValue(e.target.value)} />
</div>
{fabbutton.map((val, key) => {
return (
<button key={key} onClick={() => val.onClick()}>
<p>{val.label}</p>
</button>
)
})}
</div>
);
}
export default App;