In React, how do I detect if my component is rendering from the client or the server?

前端 未结 9 1284
夕颜
夕颜 2020-12-29 18:41

I\'m building a isomorphic application, but I\'m using a third-party component that only renders on the client. So, particularly for this component, I need to only render it

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 19:29

    You can create one useful utility with the help of the exenv package.

    import { canUseDOM } from 'exenv';
    
    export function onClient(fn: (..._args: any[]) => any): (..._args: any[]) => any {
        if (canUseDOM) {
            return fn;
        }
    
        if (process.env.NODE_ENV === 'development') {
            console.log(`Called ${fn.name} on client side only`);
        }
    
        return (): void => {};
    }
    

    And use it like this

    function my_function_for_browser_only(arg1: number, arg2: string) {}
    
    onClient(my_function_for_browser_only)(123, "Hi !");
    

    And the function will only be called on client side, and it will log on server side that this function has been called on client side if you set NODE_ENV=development

    (It's typescript, remove types for JS :) )

提交回复
热议问题