Christian Grabowski
Christian Grabowski

Reputation: 2892

Is there a way in react to tell if it is react native or web?

I have a bunch of react components that I'm hoping I can use for both web and native. The way I am trying to do that is like so:

React.createClass({
    getInitialState: function(){
        return {isMobile: <some way of tell is native or web>};
    },
    render: function(){
        if(this.state.isMobile){
            return <SomeIosComponent/>
        }
        else{
            return <div/>
        }
    }
});

I'd like to be able to do this so I can keep the logic the same for something that appears to be the same on web and native, is this possible? Could it be as simple as {isMobile: (window ? false : true)}? Or does window exist in native so there is a way to define globals within a local scope for some odd reason?

I know this goes against the React philosophy of "Learn once, write anywhere".

Upvotes: 5

Views: 4141

Answers (1)

eddyjs
eddyjs

Reputation: 1280

Like you said, this goes against the React philosophy, so I wouldn't recommend it.

However, there is a way to determine which React you're using if you really want to use this method. This might feel a bit hacky, but React Native has many properties that React does not. So when you write your components, you can check if React.View exists. If it does, you're using React Native. Otherwise, you're using the web version.

React.createClass({
    getInitialState: function(){
        return {isMobile: React.View !== undefined };
    },
    render: function(){
        if(this.state.isMobile){
            return <SomeIosComponent/>
        }
        else{
            return <div/>
        }
    }
});

Upvotes: 5

Related Questions