Frazko
Frazko

Reputation: 27

How to apply absolute position to custom Component in React Native?

this something stange but as you can see here: https://snack.expo.io/B1_5TLFvW the custom component "Cualquiera" is not positioning with absolute position, it's showing in stack, just like a list, and View components are good, if I change "class Cualquiera extends to Component" to "class Cualquiera extends View" it then it takes the position correctly, I have a custom component in my code that is not taking the absolute positions even if I set it to extend View, it shows the components as list too. How can I make it work with absolute positions extending Component?

thank you!!

here the code

import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default class Position extends Component {
render() {
    return (
    <View style={styles.container}>


        <Cualquiera numero={1} style={styles.box1} />
        <Cualquiera numero={4} style={styles.box4} />

        <View numero={2} style={styles.box2}><Text style={styles.text}>2</Text></View>
        <View numero={3} style={styles.box3}><Text style={styles.text}>3</Text></View>


    </View>
    );
}
}

class Cualquiera extends Component {
render() {
    return (
    <View
        style={{
        backgroundColor: '#49f',
        borderWidth: 0.5,
        borderColor: '#f05',
        padding: 20,
        }}>
        <Text style={styles.text}>{this.props.numero}</Text>
    </View>
    );
}
}

const styles = StyleSheet.create({
container: {
    // flex: 1
},
box1: {
    position: 'absolute',
    top: 40,
    left: 40,
    width: 100,
    height: 100,
    backgroundColor: 'red',
},
box2: {
    position: 'absolute',
    top: 80,
    left: 80,
    width: 100,
    height: 100,
    backgroundColor: 'blue',
},
box3: {
    position: 'absolute',
    top: 120,
    left: 120,
    width: 100,
    height: 100,
    backgroundColor: 'green',
},
box4: {
    position: 'absolute',
    top: 160,
    left: 160,
    width: 100,
    height: 100,
    backgroundColor: 'yellow',
},
text: {
    color: '#ffffff',
    fontSize: 40,
},
});

Upvotes: 1

Views: 1016

Answers (1)

Funk Soul Ninja
Funk Soul Ninja

Reputation: 2183

The Cualquiera component is a custom component. The styles prop you pass into it isn't used for styling. If you want to pass in styles, pass in the style prop into view style prop like this:

class Cualquiera extends Component {
  render() {
    return (
      <View
        style={[
          { backgroundColor: 'blue'}, // pass in your main styles here
          this.props.style // styles passed by props will be used
        ]}
      />
    )
  }

Upvotes: 1

Related Questions