Preventing style conflicts in react-native with styled-components

Attempting to customize the properties of a button in the calling component using styled-components, but encountering issues. The overriding of properties does not seem to be successful, and the button appears unchanged.

The button is defined as follows:

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

type ButtonProps = {
  text: string;
};

export const RegularButton = ({text}: (ButtonProps)) => {

  var [ isPress, setIsPress ] = React.useState(false);

  var touchProps = {
    activeOpacity: 1,
    underlayColor: '#111111',
    style: isPress ? (styles.btnPress) : (styles.btnNormal),
    onHideUnderlay: () => setIsPress(false),
    onShowUnderlay: () => setIsPress(true),
    onPress: () => console.log('HELLO'),
  };

  return (
    <TouchableHighlight  {...touchProps}>
      <Text style={styles.textStyle}>{text}</Text>
    </TouchableHighlight>
  );
}

var styles = StyleSheet.create({
  btnNormal: {
    backgroundColor: '#333333',
    borderColor: 'black',
    borderWidth: 1,
    borderRadius: 10,
  },
  btnPress: {
    borderColor: 'black',
    borderWidth: 1,
    borderRadius: 10,
  },
  textStyle: {
    color: '#a7a7a7',
    margin: 'auto'
  }
});

An example App module that utilizes the button and attempts to override its style using styled-components:

import React from 'react';

import styled from "styled-components";
import { RegularButton } from './components/core/RegularButton'

const MainView = styled.div`
  width: 100%;
  height: 100%;
  background-color: #1a1a1a;
  flex: 1;
  align-items: 'center';
  justify-content: 'center';
`;

const LevelButton = styled(RegularButton)`
  width: 100%;
  height: 60px;
  margin-left: 16px;
  margin-right: 16px;
`;


export default function App() {
  return (
    <MainView>
      <LevelButton text={"hello"}/>
      <LevelButton text={"hello"}/>

    </MainView>
  );

Trouble arises as the button fails to adopt the overridden width, height, or margin properties. What could be causing this issue?

Answer №1

It seems like your RegularButton component is not accepting the style properties as expected. To resolve this issue, you should follow these steps:

Firstly, make sure to include the style property in the ButtonProps interface:

type ButtonProps = {
  text: string;
  style?: StyleProp<ViewStyle>;
};

Next, pass the style prop to the component itself:


export const RegularButton = ({text, style}: (ButtonProps)) => {

return (
    <TouchableHighlight {...touchProps} style={style}>
      <Text style={styles.textStyle}>{text}</Text>
    </TouchableHighlight>
);

Additionally, when using react-native components with styled components, remember to import from styled-components/native instead of just styled-components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add the cordova plugin multi-image-picker with the following command

onDeviceReady: function() { window.imagePicker.getPictures( function(results) { for (var i = 0; i < results.length; i++) { alert('Image URI: ' + results[i]); } }, function ...

Header text refuses to cooperate and center itself

Struggling to find the best way to center the "Header" text while keeping the icon in place. I've tried using text-align: center;, but it's not producing the desired results. Could anyone provide guidance on how to achieve this? Thanks. IMG: ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

What is preventing me from running UNIT Tests in VSCode when I have both 2 windows and 2 different projects open simultaneously?

I have taken on a new project that involves working with existing unit tests. While I recently completed a course on Angular testing, I am still struggling to make the tests run smoothly. To aid in my task, I created a project filled with basic examples f ...

Troubleshooting problem with responsive image display and blurred effects

Initial problem I have a photo gallery on my website. When you click on a photo, you can view a larger preview. To cater to mobile users, I set the following CSS: .overview img { height: auto; width: 90%; } However, I am facing an issue where the hei ...

Tips for implementing lazy loading with an owl carousel featuring background images

Is there a way to add lazy loading to a semi custom owl carousel that uses background images instead of regular img tags? I've tried using Owl carousel's function for lazy loading but it doesn't seem to work. How can I achieve this? This is ...

Using namespaces in Rails to encapsulate CSS styles

Is there a way to add namespaces to CSS within a Rails project? I have two pre-defined CSS files and two application layouts. I want the first layout to use one CSS file, and the second layout to use the other. However, both CSS files have styles for the ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

I am having trouble with my scroll reveal effects on JavaScript, how can I troubleshoot and fix the issue?

I'm currently making updates to my portfolio website, but for some reason, the scroll reveal animation has suddenly stopped working. I made a few edits and now it seems to be broken. /*===== SCROLL REVEAL ANIMATION =====*/ const sr = ScrollReveal({ ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

Error: Router service provider not found in Angular 2 RC5!

Having trouble with using this.router.navigate. Here is the content of my app.module.ts file: import {NgModule, NgModuleMetadataType} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; im ...

Choose a Different Value for Another HTML Element's Class

Is there a way to preselect an option on another page before it loads? Consider two pages, A and B. If a user clicks a button on page A, I want the default option on page B to be changed to "something" before redirecting them. How can this be achieved s ...

Error copying cell width attribute when using border collapse

Currently, I am attempting to duplicate a table header by copying the tr HTML and then replicating the th widths. Unfortunately, this method is unsuccessful as the widths are displayed as (width minus W) pixels when border: 'Wpx' and border-colla ...

Find the TypeScript data type of an array that may be empty

Struggling to determine the TypeScript type of data being passed into my React component. The data could either be related to cats or dogs: my-component.tsx: export const MyComponent = { props: { data: any; // Ideally looking to utilize the union type & ...

What is the best way to centrally position a <mat-card> on the screen using Angular 9?

* I'm struggling to center a <mat-card> on the screen, specifically within the toggle-device-toolbar. It's intended for mobile phones and I could use some guidance. I'm working with angular-material and ng-bootstrap* Here is the code ...

What steps can be taken to expand the axis space in recharts to accommodate an additional label?

I'm struggling to display an additional label below my X-Axis label as it keeps getting clipped off. https://i.sstatic.net/ftI7w.png Below is the code snippet for my XAxis: <XAxis type="number" tick={<CustomizedNumberTick lang={props ...

Performing addition in Angular 2 with the help of TypeScript

Here is a code snippet of a component I have written: export class AppComponent { public num1: number = 2; public num2: number = 3; public sum: number = 0; public add() { this.sum = this.num1 + this.num2; } } However, when I r ...

Using TypeGraphQL with Apollo Server for File Uploads

What I'm Striving to Achieve I am attempting to implement file uploads using typegraphql (a wrapper on Apollo Server). I have created a basic resolver that is supposed to receive a file upload and save it to the server. The Code I'm Using This ...

What could be causing spacing problems with fontawesome stars in Vue/Nuxt applications?

Currently, I am working on implementing a star rating system in Nuxt.js using fontawesome icons. However, I have encountered an issue where there is a strange whitespace separating two different stars when they are placed next to each other. For instance, ...

In Angular, the data retrieved from the API will only appear on the page once it has been manually

Recently, I started working on an Angular project and encountered a problem with data display after each component routing. Initially, the data is not displayed until the page is reloaded. You can see the issue in the screenshots: https://i.sstatic.net/5My ...