16

I need to align a button, which is not at the bottom of the screen by design, to be in the middle of the screen. However, it should align to be on top of the keyboard for all devices.

If you check this screenshot :

enter image description here

For some devices, I managed to achieve this alignment, but on others, it's not perfectly aligned.

enter image description here

how can I manage this to work in all?

this is what I did so far :

<Padding paddingVertical={isKeyboardOpen ? Spacing.unit : Spacing.small}>
<Button
      variant="solid"
      label='Next'
      style={styles.submitBtn}
    />

</Padding>

And isKeyboardOpen is just a method which will create a listner based on the platform return true if keyboard is open :

 Keyboard.addListener(
  Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
  true 
 );

And submitBrn css class is :

submitBtn: {
  margin: Spacing.base,
},
2

3 Answers 3

22

First import this packages

import {
  Button,
  ScrollView,
  KeyboardAvoidingView,
  TextInput,
} from 'react-native';

Render method

 <KeyboardAvoidingView
  {...(Platform.OS === 'ios' ? { behavior: 'padding' } : {})}
  style={styles.container}>
  <ScrollView style={styles.scrollView}>
    <TextInput style={styles.input} placeholder="Tap here" />
  </ScrollView>
  <Button title="Next" />
</KeyboardAvoidingView>

This are the styles

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    paddingHorizontal: 20,
  },
  input: {
    marginBottom: 20,
    borderBottomWidth: 2,
    borderColor: '#dbdbdb',
    padding: 10,
  },
});

Make sure the button is outside the scrollview.

NOTE: You may need to adjust the offset prop of KeyboardAvoidingView if the keyboard has got autocomplete enabled.

Stick button at the bottom of the screen demo

5
  • not really, I already went through KeyboardAvoidingView, but my case is different, keyboards in different platforms ( ios, android ) and different devices have different sizes, and my button by design it must located in middle of screen before textbox is focused, and when is focused then it should be stuck on top of the keyboard for all platforms and devices. in your example button is at bottom of screen and there are no need to adjust the button. Commented Feb 1, 2019 at 8:12
  • It happend when keyboard show up and scroll on input Commented May 16, 2020 at 10:25
  • Does this ONLY work on Android for anyone else? Commented Jun 30, 2021 at 17:28
  • 1
    No, It works for both android & ios. I will check again with the latest version. Commented Jun 30, 2021 at 18:27
  • 1
    @GrantSingleton thanks for catching the bug, in the latest version we don't need a behaviour prop for android. Commented Jul 4, 2021 at 8:29
4

In case anyone is still looking for a solution to this I am posting a working example from October 2021 along with the react native documentation. This example is for a text input that when focused has a button labeled 'Scanner' above the keyboard. React native documentation refers to what we are creating here as a 'toolbar'.

Please see this for further details https://reactnative.dev/docs/next/inputaccessoryview

import {
  Button,
  ScrollView,
  TextInput,
  StyleSheet,
  InputAccessoryView,
  Text,
  View,
} from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { BarCodeScanner } from "expo-barcode-scanner";
import { useFocusEffect } from "@react-navigation/native";

function CreateSearchBar() {
  const inputAccessoryViewID = "uniqueID";
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);
  const [showScanner, setShowScanner] = useState(false);

  useEffect(() => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === "granted");
    })();
  }, []);

  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused
      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
        setShowScanner(false);
      };
    }, [])
  );

  onChangeSearch = (search) => {};

  setScannerShow = (show) => {
    setShowScanner(show);
  };

  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    setShowScanner(false);
    alert(`Bar code with type ${type} and data ${data} has been scanned!`);
  };

  if (hasPermission === null) {
    return <Text>Requesting for camera permission</Text>;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  if (showScanner) {
    return (
      <View style={styles.scanner}>
        <BarCodeScanner
          onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
          style={StyleSheet.absoluteFillObject}
        />
        {scanned && (
          <Button
            title={"Tap to Scan Again"}
            onPress={() => setScanned(false)}
          />
        )}
      </View>
    );
  }

  return (
    <>
      <ScrollView keyboardDismissMode="interactive">
        <View style={styles.input}>
          <MaterialCommunityIcons name="magnify" size={24} color="black" />
          <TextInput
            onChangeText={onChangeSearch}
            inputAccessoryViewID={inputAccessoryViewID}
            placeholder="Find items or offers"
          />
          <MaterialCommunityIcons
            name="barcode"
            size={30}
            color="black"
            onPress={() => setScannerShow(true)}
          />
        </View>
      </ScrollView>
      <InputAccessoryView nativeID={inputAccessoryViewID}>
        <Button onPress={() => setScannerShow(true)} title="Scanner" />
      </InputAccessoryView>
    </>
  );
}
const styles = StyleSheet.create({
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    padding: 10,
    flexDirection: "row",
    justifyContent: "space-between",
  },
  scanner: {
    height: "50%",
  },
});

export default CreateSearchBar;
1
  • Be aware that, as stated in the documentation, InputAccessoryView is an iOS only feature. Commented Nov 23, 2023 at 9:56
-2

YOu can use react native modal

 <KeyboardAvoidingView
    keyboardVerticalOffset={Platform.OS == "ios" ? 10 : 0}
    behavior={Platform.OS == "ios" ? "padding" : "height"} style={{ flex: 1         }} >
    <Modal>

       <ScrollView>  
      <Content><-------Your content------></Content>
       </ScrollView>  

      <BottomButton   />
    </Modal>
  </KeyboardAvoidingView>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.