In my app, I have several components that I’m using and I need to pass a parameter to it from the selected value in my drop down. How can I pass the value to the component and load a table? (data is from an API)
The app is setup as: The component with the dropdowns (I’ll show one for this)
service.js
import ServiceCustomerNotes from '../details/customerNotes'
const viewServiceCalls = () => {
useEffect(() => {
getServiceNotes(id); //id is passed from a menu option
}
const serviceChange = async() => {
setCustomerId({ ...customerId, customerId: e.target.value});
}
return (
<div>
<!-- for simplicity option values are hardcoded -->
<select name="serviceNotes" onChange={serviceChange}>
<option value="0">Select Customer</option>
<option value="1">Smith</option>
<option value="2">Jones</option>
</select>
</div>
<div>
<ServiceCustomerNotes
noteId={}
/>
</div>
)
}
The customer service notes component
const SericeCustomerNotes = ({ noteId }) => {
// this is where I'm stuck, how do I get the noteId from the dropdown on the serice.js
component? I have my calls to the API to get data working (hardcoded for testing), I need to
get the noteId passed into this.
}
>Solution :
const viewServiceCalls = () => {
const [customerId, setCustomerId] = useState(0);
useEffect(() => {
getServiceNotes(id); //id is passed from a menu option
}, []);
const serviceChange = (e) => {
setCustomerId(e.target.value);
};
return (
<div>
<div>
<select name="serviceNotes" onChange={serviceChange}>
<option value="0">Select Customer</option>
<option value="1">Smith</option>
<option value="2">Jones</option>
</select>
</div>
<div>
<ServiceCustomerNotes noteId={customerId} />
</div>
</div>
);
};
Guess this is what you want.
Explanation: hook useState will hold the current customerId, whenever you call setCustomerId (which is returned from useState) the component will re-render and update value will be passed to ServiceCustomerNotes component