Dan Dan - 3 months ago 24
React JSX Question

React native view layer

I'm trying to put a white dot over a green square like below.

separate

But no matter how I try I still get this. The background color and margin of the white dot is gone.

overlay

Here's the code.

<View style={backgroundColor: 'white', zIndex: 1, margin: 2, borderRadius: 10, borderWidth: 2} >
<View style={backgroundColor: 'green', zIndex: 0} />
</View>


I though zIndex will solve my problem but it doesn't. I've also tried swapping the order but it just give me a plain green square. Help?

<View style={backgroundColor: 'green', zIndex: 0}>
<View style={backgroundColor: 'white', zIndex: 1, margin: 2, borderRadius: 10, borderWidth: 2} />
</View>


enter image description here

Answer

I don't think you need/want to use z-index for this. z-index is used for depth, to layer items that occupy the same space.

Read up on it here: CSS Tricks - z-index

I'd agree that you want to make use of flexbox if you're trying to keep everything aligned.

Here's an example:

<View style={styles.container}>

    <View style={styles.holder}>
      <View style={styles.circleHolder}>
            <View style={styles.circle} />
      </View>
      <View style={styles.square} />
    </View>

</View>

and the styling:

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    circleHolder: {
        width: 200,
        height: 200,
        justifyContent: 'center',
        alignItems: 'center'
    },
    circle: {
        backgroundColor: 'white',
        width: 150,
        height: 150,
        borderRadius: 75,
        borderWidth: 2
    },
    square: {
        backgroundColor: 'green',
        width: 200,
        height: 200,
    },
});

RNPlay: https://rnplay.org/apps/k5DbDQ