I want to check user access from wrapper component before clicking on a button(or before a button onClick function fires).
Here is the button component
<UltimateButton
btntext="+ New document"
classes="btn-primary"
handleClick={create_new_doc}
/>
Here handleClick
fires onClick function (create_new_doc
). And suppose I have a wrapper component <AccessControl>
that wraps this button component. I want to check access when clicking AccessControl
before create_new_doc
is fired.
I wrote like this
import React, { Children, cloneElement } from "react";
const AccessControl = ({children}) => {
const checkUserAccess = () => {
console.log('Access denied')
}
return {...children}
}
export default AccessControl;
Now if access is denied in AccessControl
then create_new_doc
won’t fire anymore. How can I accomplish it. I also tried clone element.
This will be used like this
<AccessControl>
<UltimateButton
btntext="+ New document"
classes="btn-primary"
handleClick={create_new_doc}
/>
</AccessControl>
2
Answers
You can do this in many ways. If you want to keep a similar flow ( using access wrapper) then you should have the wrapper itself handle the on click to conditionally render the button.
Here is one simple way to do this (as aforementioned there are MANY ways to do this, let me know if you’d like a different version):
Usage:
Seems like you are on the right track with the idea of cloning the child component.
Clone the child component and re-inject a "decorated"
handleClick
prop that first makes a call tocheckUserAccess
and if this function returns true or confirms the user has access then it calls the originally passedhandleClick
callback.Example:
Demo