Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add component in react

My code looks to somethis like

<iOSOnlyComponent>
.....
.....
.....
</iOSOnlyComponent>

Want to use the iOSOnlyComponent only on iOS. I tried this

{isIOS && <iOSOnlyComponent>}
.....
.....
.....
{isIOS && </iOSOnlyComponent>}

But I got a syntax error

like image 822
j.doe Avatar asked Sep 17 '25 11:09

j.doe


2 Answers

You should do something like (untested code)

 render() {
    const helloMessageIOS = <iOSOnlyComponent> Hello, JSX! </iOSOnlyComponent>;
  return (
    <ScrollView >
       {isIOS  && helloMessageIOS   }
    </ScrollView >
  );
}

If iOSOnlyComponent component is huge, you can simply add it to a function and return it from there.

May be as below (untested code)

render() {
    return (
    <View >
       {isIOS  && {this.displayComponent()}   }
    </View >
  );
}


displayComponent() {
   return <iOSOnlyComponent> Hello, JSX! </iOSOnlyComponent>;
}
like image 117
G_S Avatar answered Sep 20 '25 03:09

G_S


If the conditionnal rendering makes your component too complex you can simply separate it in 2 files naming them myComponent.android.js and myComponent.ios.js then simply import myComponent from './myComponent'

React will choose the right file automatically.

like image 22
Dyo Avatar answered Sep 20 '25 03:09

Dyo