I have created a custom MenuList
button ("Add New User") at the bottom of a React-Select
element to allow for adding another user to the select list. However, I am having trouble figuring out how to handle the event once a new user is created. The codesandbox below contains a simplified version. Specifically, line 29 this._loadData(randomId)
does not have the scope to access this
of the parent component (obviously). My question is, how to I add a "handleEvent" property so that I can lift up state to the parent component for this custom MenuList
component?
Code snippet for the custom MenuList
component allowing the user to add a new AppUser:
const MenuButtonAddNewUser = (props) => {
return (
<components.MenuList {...props}>
{props.children}
<div className="border-top text-center py-2">
<a
href="showModalUrl.action"
onClick={(event) => {
event.preventDefault();
// Simluate opening a modal and adding a user
let randomId = Math.floor(Math.random() * (10 - 4 1)) 4;
console.log(
"Simluate loading modal and adding a user with id: " randomId
);
// Tell parent componenent to reload the options from the database
// and auto-select the new user
// How do I gain access to "_loadData"???
//this._loadData(randomId);
console.log(
"User added. Call 'this.loadData(" randomId ")' here!!"
);
}}
>
<i className="fa fa-fw fa-user-plus mr-1" /> Add New Agent
</a>
</div>
</components.MenuList>
);
};
CodePudding user response:
I'm not familiar with react-select's API, but one approach you could take is to convert the class component to a function component. You could then move the MenuButtonAddNewUser
component into the App component, this will give it access to everything App has access to.
CodeSandbox link with the suggestion: https://codesandbox.io/s/react-select-custom-event-handler-forked-n0v21o?file=/src/App-Hooks.js