Home > Blockchain >  How to apply elevation to TouchableOpacity in react native?
How to apply elevation to TouchableOpacity in react native?

Time:09-28

I am using android in react native.

I have a TouchableOpacity of FirstButton and SecondButton. I gave the SecondButton a position absolute but gave the FirstButton an elevation so that the FirstButton overwrites the SecondButton.

FirstButton overwritten SecondButton, the problem is that when I run onPress, secondfunc fires. I expected secondfunc to fire because FirstButton overrides SecondButton

Why is this happening? How should I fix this?

this is my code

    import React from 'react';
    import styled from "styled-components/native";
    import { Text, View, StyleSheet } from "react-native";

    const FirstButton = styled.TouchableOpacity`
    width: 100px;
    height: 40px;
    background: lavender;
    `;

    const SecondButton = styled.TouchableOpacity`
    position: absolute;
    top:0;
    bottom:0;
    right:0;
    left: 5%;
    width: 100px;
    height: 40px;
    background-color: lightpink;
    `;

    const App = () => {


      const firstConfunc = () => {
        console.log("firstConfunc");
      }

      const secondfunc = () => {
        console.log("secondconfuc");
      }
      return (
        <>
          <FirstButton
            onPress={firstConfunc}
            style={styles.FirstButton}
          // style={{ zIndex: 1 }}
          >

            <Text>FirstContain</Text>
          </FirstButton>



          <SecondButton
            style={styles.SecondButton}
            onPress={secondfunc}>
            <Text>secondContainer</Text>
          </SecondButton>

        </>
      );
    };

    const styles = StyleSheet.create({
      FirstButton: {
        elevation: 4
      },
      SecondButton: {
        elevation: 1
      }
    })

    export default App;

CodePudding user response:

Please try something like this:

  main: {
    flex: 1,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 5,
    },
    shadowOpacity: 0.10,
    shadowRadius: 6.27,
    elevation: 10,
  },

CodePudding user response:

Wrap your TouchableOpacity inside a View :-

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
     <View style={{ backgroundColor:'white', elevation: 5}}>
      <TouchableOpacity style={{padding: 20}} onPress={() => console.log("Pressed")}>
      <Text>Press Me! </Text>
      </TouchableOpacity>
     </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});
  • Related