How to use Platform.OS to elements in react native?
Asked Answered
A

7

34

I want to use just KeyboardAwareScrollView without any functions on IOS and given below code for android.

I know that I need to use Platform.OS === 'ios' ? :

BUT I DON'T UNDERSTAND HOW TO REALISE IT. Please help me

render(){
 return(

    <KeyboardAwareScrollView
       extraScrollHeight={100}
       enableOnAndroid={true}
       keyboardShouldPersistTaps='handled'
    >
      <TextInput
        style={styles.inputContainerStyle}
        label="Username"
        value={this.state.username}
        onChangeText={username => this.setState({ username })}
      />
    </KeyboardAwareScrollView>
   )
}

What I've tried below: (But it doesn't work)

<KeyboardAwareScrollView
      Platform.OS === 'android' ? 
      (
         extraScrollHeight={100}
         enableOnAndroid={true}
         keyboardShouldPersistTaps='handled'
      ) : null
  >
Anglocatholic answered 20/7, 2018 at 7:4 Comment(1)
You can get your answer here in this questionPertinacious
F
43

You can also check via node but react-native provides some ways to check platform.

This one is recommended

 import {Platform} from 'react-native';
    st styles = StyleSheet.create({
      container: {
        flex: 1,
        ...Platform.select({
          ios: {
            backgroundColor: 'red',
          },
          android: {
            backgroundColor: 'blue',
          },
        }),
      },
    });

You can also use ternary expressions

 import {Platform, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
  height: Platform.OS === 'ios' ? 200 : 100,
});

Read this

Fourfold answered 17/10, 2018 at 16:35 Comment(0)
T
12

You can use JSX prop spread and a ternary expression at the same time:

<KeyboardAwareScrollView
  {
    ...(Platform.OS === 'android' ? 
    { 
      extraScrollHeight={100}
      enableOnAndroid={true}
      keyboardShouldPersistTaps='handled'
    } : {})
  }
>

I highly recommend against doing this all inline though, since it's hard to read. You could do something a bit readable (and declarative) using Platform.select:

const keyboardProps = Platform.select({
  android: { … },
  ios: {},
});
…
<KeyboardAwareScrollView {...keyboardProps}>
Terpene answered 20/7, 2018 at 7:11 Comment(3)
Where I should add const keyboardProps ? before class declared? inside class? or inside return statement?Anglocatholic
first code can't read height 100, snack.expo.io/Hkd-9MkEQ, you can check hereAnglocatholic
@JustAhead You need to add the opening tag.Terpene
U
3

If you want to keep your code much simpler and cleaner to understand, do this: For example, if you want to specific "marginTop" per specific operating System. You can do this:

 <View style={{justifyContent:'center',marginTop:Platform.select({
            ios: '30%', //30 percent of margin is applied to IOS
            android:'10%', // 30 percent of margin is applied to Andriod

          })}}>

Go to this website by React-native: https://reactnative.dev/docs/platform-specific-code for more information.

Unsphere answered 10/9, 2020 at 22:5 Comment(0)
B
3

Try this one,

renderKeyboardAwareScrollView(){
  if(Platform.OS === 'ios'){
    return (
       <KeyboardAwareScrollView
       extraScrollHeight={100}
       enableOnAndroid={true}
       keyboardShouldPersistTaps='handled'
    >
      <TextInput
        style={styles.inputContainerStyle}
        label="Username"
        value={this.state.username}
        onChangeText={username => this.setState({ username })}
      />
    </KeyboardAwareScrollView>
    )
  } else {
    return (
      <TextInput
        style={styles.inputContainerStyle}
        label="Username"
        value={this.state.username}
        onChangeText={username => this.setState({ username })}
      />
    )
  }
}
render(){
 return(
  {this.renderKeyboardAwareScrollView()}
 )
}
Burse answered 11/9, 2020 at 4:29 Comment(0)
W
2

This syntax works for me:

 keyboardProps = Platform.select({
    android: {
      enabled: true,
      keyboardVerticalOffset: 0
    },
    ios: {
      enabled: true,
      keyboardVerticalOffset: 64,
      behavior: 'height',
    },
  });

  render = () => (

    <KeyboardAvoidingView 
      {...this.keyboardProps}
    >
Wallet answered 27/2, 2020 at 8:31 Comment(0)
G
1

use bracket {} for Ternary Condition inside return ()

so your code looks like :

render(){
 return(
 <View>
 { ...Platform.OS === 'android' 
    ? //if true
    <KeyboardAwareScrollView
       extraScrollHeight={100}
       enableOnAndroid={true}
       keyboardShouldPersistTaps='handled'
    />
    : //if false
    <KeyboardAwareScrollView
      //your props for else condition
    />
    // or add null if you don't want to add another
 }
      <TextInput
        style={styles.inputContainerStyle}
        label="Username"
        value={this.state.username}
        onChangeText={username => this.setState({ username })}
      />
  </View>
   )
}

EDITED:

add spread notation(...) to make it work at Platform.OS

Prove:

code

screen

Gallbladder answered 20/7, 2018 at 7:13 Comment(8)
can you check, please, it says unterminated JSX contents snack.expo.io/HJWSdM1NQAnglocatholic
@JustAhead if you dont need to handle the iOS KeyboardAwareScrollView just use null snack.expo.io/Bked2KMkNQGallbladder
@JustAhead here's a fixing, you cant put the closed tag of component outside {}Gallbladder
@Gallbladder Huh, you're right, it does work. Seems like Babel is cloning the element, but it's incredibly hard to read IMO. But your first example doesn't work. You can't have adjacent tags after the ternary, Babel cannot parse it.Terpene
@Li357 I'm not aware of the code, i just add my code from existing code, but you're right, the 3rd line from bottom (</KeyboardAwareScrollView>) should be deleted to make it work,Gallbladder
The text input right after is also invalid syntax. You'd have to wrap them in a container, or use keys/fragments.Terpene
@Li357 again, i'm too lazy to test the code, now i think i'm done to edit the answerGallbladder
This will not work with nested components cos the top level should be closedConation
F
0

In order to add keyboard awareness to iOS part of react native app just add

  pod 'IQKeyboardManager'

in podfile and run pod install inside ios folder. It will enable IQkeyboard in your iOS app and will save you from hasle.

Gotcha: You might have to re add the pod file if some how your ios project is reset.

Followup answered 6/8, 2019 at 5:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.