Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling custom component in react native

Tags:

react-native

I am trying to add styling to my custom component in react native, but no matter what I do, the style has no effect. Here is my code:

// App.js
import MyCustomComponent from './components/myCustomComponent.js';

render() {
  return (
    <View style={styles.container}>
      <MyCustomComponent style={{marginTop: 10}}/>
    </View>
  );
}

The project compiles fine, and my custom component appears on screen fine, but the marginTop styling is not applied. It is worth noting that the style for the parent View component does apply correctly. This is a brand new project I just created today. This seems like it should be extremely basic, but just isn't working. What can I do to apply this styling?

Custom component code:

import React, {Component} from 'react';
import {TextInput, StyleSheet, Image, View, Button} from 'react-native';

type Props = {};
export default class MyCustomComponent extends Component<Props> {

  render() {
    return (
      <View style={styles.container}>
        <Image
          source={{ uri: "source here" }}
          style={{ width: 50, height: 50 }}
         />
         <TextInput
          style={{ height: 50 }}
          placeholder="Search"
        />
      </View>
    )
  }
}

1 Answers

you can use this code:

export default class MyCustomComponent extends Component<Props> {
  render() {
    return (
      <View style={[styles.container, {...this.props.style}]}>
        ...
      </View>
    )
  }
}

now, styles.container is applied and anything you pass to component through style will be added to component style.

I hope this can help you

like image 163
Ali SabziNezhad Avatar answered Sep 23 '25 04:09

Ali SabziNezhad