简体   繁体   中英

Passing components/JSX as a prop to the child component without using this.props.children

Im trying to create a helper component that would help me check if the user has the permission to carry out a certain action. This helper component is called PermissionsChecker and it will wrap around the JSX of interest.

The issue im facing now is that i wish to be able to specify some JSX to be rendered if the check fails, for example, some jsx containing texts that they are not authorized.

Heres the code to further illuminate on the problem:

class PermissionsChecker extends Component {
    checkperms(){
       //code which checks the user's permissions list
    }
    
    render() {
        if(this.checkperms() === true){
        return (
            this.props.children //<-- i will return whatever JSX it was wrapping.
            )}
        else{
        return(
            (this.props.replacement?
                <Fragment>
               {this.props.replacement}  //<--- here is where i wish to return the JSX if check fails
                </Fragment>
            )
        )
        }
    }
}

Here is the helper function in action:

<PermissionsChecker
   codeNames={['view_salesprojec2t']}
   replacement={<Text>{id}</Text>} >
   <Link to={`/project/detail/${id}`}>
   {id}
   </Link>
</PermissionsChecker>

As you can see, this.props.children will not be a solution for me as i am already utilizing that to return the original JSX. What i wish to do is to add the ability to specify the JSX in the replacement prop and then returning it back from my PermissionsChecker component if the check passes.

I have tried to console log this.props.replacement and I am recieving this:

{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
$$typeof: Symbol(react.element)
key: null
props:
children: 1
__proto__: Object
ref: null
type: ƒ Text(_a)
_owner: FiberNode {tag: 11, key: null, elementType: {…}, type: {…}, stateNode: null, …}
_store: {validated: false}
_self: CustomerDetail {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternalFiber: FiberNode, …}
__proto__: Object

Is there a good fix for this?

Passing a constructed component ( <Component/> ) throught props is an anti-pattern.

Instead, you should use conditional rendering on props.children , while checking the condition on component's level (instead of using PermissionsChecker ):

<>
  {checkPermissions() ? (
    <Link to={`/project/detail/${id}`}>{id}</Link>
  ) : (
    <Text>{id}</Text>
  )}
</>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM