Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass style props for a specific component in react-native

I tried creating a button with specific styles for its . I had more than 3 properties like justifyContent, alignItems, backgroundColor and height. I wanted to pass a style from another component to this, so that the backgroundColor property of the button changes.

My Code:

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';

const Button = ({ buttonName, csCode }) => {
  const { buttonStyle, textStyle } = styles;

  return (
    <TouchableOpacity style={{ buttonStyle, backgroundColor: [csCode] }}>
      <Text style={textStyle}>
      {buttonName}
      </Text>
    </TouchableOpacity>
  );
};

const styles = {
  textStyle: {
    alignSelf: 'center',
    color: '#ffffff',
    fontSize: 35,
    fontWeight: '600',

  },
  buttonStyle: {
    justifyContent: 'center',
    alignSelf: 'stretch',
    height: '20%',
  }
};

export { Button };

Here, the buttonStyle is not applied to the buttons, instead only the backgroundColor prop is only being applied. Any help ?

Thanks.

like image 569
Amirth Avatar asked Jan 06 '18 21:01

Amirth


People also ask

How do you pass props in component React Native?

After we import the PresentationalComponent and pass it to the render function, we need to pass the props. We will pass the props by adding myText = {this. state. myText} and deleteText = {this.

How do you pass styles to component React?

Use the React. CSSProperties type to pass CSS styles as props in React TypeScript, e.g. style: React. CSSProperties; . The CSSProperties type is used to type the style object that consists of CSS property names and values.

How do you style components in React Native?

With React Native, you style your application using JavaScript. All of the core components accept a prop named style . The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g. backgroundColor rather than background-color .

Can I pass props to styled component?

Passed propsIf the styled target is a simple element (e.g. styled. div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.


1 Answers

If you want to use styles from the styles object and inline styles together, please put them in an array like this:

<TouchableOpacity style={[buttonStyle, {backgroundColor: csCode }]}>
  ...
</TouchableOpacity>
like image 171
moritzw Avatar answered Oct 22 '22 06:10

moritzw