Conditionally linking with react-router Link

后端 未结 3 613
孤城傲影
孤城傲影 2021-01-12 08:21

I have a situation in my React component which is: i want some elements to be wrappend in a Link component if this.props.isComingFromModal is false

3条回答
  •  独厮守ぢ
    2021-01-12 08:47

    Maybe this is late, but despite evan's answer is correct, either of cases didn't work for me. Maybe due to some additional incorrect imports I've made or what... But it has inspired me to another similar solution, that worked just fine for me, so I want to share it here for those being in similar situation like me.

    This solution will instead of putting the content into a variable rather create a simple ConditionalLink component that would accept any content as children with other required props but at least the condition and path to.

    render() {
        const {children, to, condition} = this.props;
        let toRender;
    
        if (condition) {
            toRender = {children};
        } else {
            toRender = children;
        }
    
        return toRender;
    }
    

    Good thing on it is you could later reuse it again with any other content. For example:

    
        ...content...
    
    

提交回复
热议问题