Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure:

import { StyleSheet } from 'react-native';
import { Input, Item } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { moderateScale, verticalScale } from 'react-native-size-matters';
import { styles as commonStyles } from '~/styles/RegistrationStyles';

type FieldInputProps = {
  handleChange: (e: string) => undefined;
  handleBlur: (e: string) => undefined;
  value: string;
  fieldType: string;
  placeholderText?: string;
  hidePasswordIcon?: string;
  hidePassword?: boolean;
  togglePassword?: () => void;
  icon: string;
};

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
}) => {
  return (
    <Item rounded style={styles.personalListItem}>
      <Icon name={icon} size={moderateScale(20)} color="green" />
      <Input
        autoFocus={true}
        autoCapitalize="none"
        style={{ fontSize: moderateScale(15) }}
        placeholder={placeholderText}
        keyboardType="default"
        onChangeText={handleChange(fieldType)}
        onBlur={handleBlur(fieldType)}
        value={value}
        secureTextEntry={hidePassword}
      />
      {togglePassword ? (
        <Icon
          name={hidePasswordIcon}
          onPress={togglePassword}
          style={commonStyles.iconStyle}
          size={moderateScale(20)}
          color="green"
        />
      ) : null}
    </Item>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#2E3331',
    flex: 1,
  },
  personalListItem: {
    width: moderateScale(320),
    backgroundColor: 'white',
    borderBottomColor: 'grey',
    borderRadius: moderateScale(10),
    height: verticalScale(50),
    paddingRight: moderateScale(20),
    paddingLeft: moderateScale(10),
    marginVertical: moderateScale(20),
  },
  text: {
    fontFamily: 'Roboto',
    fontSize: moderateScale(20),
    fontWeight: '600',
    marginVertical: moderateScale(10),
    color: '#17D041',
  },
  subtext: {
    color: '#17D041',
    fontSize: moderateScale(14),
  },
  subtextBold: {
    textDecorationLine: 'underline',
    color: '#17D041',
    fontWeight: '600',
    fontSize: moderateScale(14),
  },
  button: {
    height: moderateScale(50),
    width: moderateScale(350),
    borderRadius: moderateScale(10),
    justifyContent: 'center',
    marginBottom: moderateScale(5),
  },
  buttonText: {
    fontSize: moderateScale(15),
  },
});

Most times when using this component, I prefer to stick to its default styling. However, in certain scenarios, I may need to override these styles. For example, adjusting the input field's width or background color. But, attempts to customize the styles don't seem to take effect.

<FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />

 fieldInput: {
    width: moderateScale(320),
    backgroundColor: 'red',
  },

Answer №1

It seems like the style prop is missing in your component. Please address this issue by following the instructions below.

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
  style,
  rounded,
}) => {
  return (
    <Item rounded={rounded} style={[styles.personalListItem, style]}>
      /* remaining code code */
    </Item>
  );
};

Answer №2

When passing styles as a parameter, such as for the outer wrap, you can implement it like this:

 <Item rounded style={[styles.personalListItem,this.props.style]}>

If a style prop is provided, it will take precedence over the personalListItem style. Otherwise, it will default to using the styles in personalListItem.

To apply styles to inner components, you need to include the style in the props and create separate style props for each component.

If you only want to use the passed style, you can do the following:

  <Item rounded style={this.props.style||styles.personalListItem}>

This will utilize the personalListItem style if no style prop is passed.

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

Ways to create a looping mechanism with specified number restrictions and limitations

Can anyone assist me with this problem? I am looking to create a "looping" effect similar to the image provided. What is the logic behind this repetition? Thank you in advance for your help! Here is an example output: ...

Stop ajax loading animation for a specific scenario

I usually have a global ajax load animation that runs during every ajax call. However, there are certain cases where I need to disable this effect. How can I achieve that? This is the code for the global animation : $(document).ajaxStart(function(){ $ ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Developing distinct state values for assigned objects

I developed a star rating component using Material UI components that is based on a mapped object. However, I am facing an issue where all the star ratings show the same value when clicked. How can I ensure that each star section displays its own value bas ...

Position child divs at the center of the parent div

I am struggling to center 3 child divs inside a parent div that must remain at a width of 100%. Can someone help me figure out how to achieve this? .parent { width: 100%; border: 1px solid blue; } .child { float: left; borde ...

The battle between Typography and HTML formatting elements

When it comes to choosing between the <Typography/> tag and normal HTML tags like <p>, I find myself in a state of ambiguity. <Box className={someClassName}> <Typography>{someVariableName}</Typography> </Box> or <p ...

Troubleshooting Cross-Origin Resource Sharing (CORS) issue when making a GET request

My application utilizes ASP.Net Core Web Api as the backend service. For the frontend, I have integrated React along with making requests to the backend API using axios. export const overviewGet = (orderId: string): Promise<IOrder> => { const U ...

Restricting the number of characters allowed for text messages and keeping track of the count

I am attempting to implement a character limiter for an html textarea using JavaScript. Additionally, I want to include a total character counter. Unfortunately, the code I have written isn't functioning as expected. Can anyone identify where my mist ...

Adjust text alignment of SVG elements using CSS

I am facing an issue where I am unable to change the x and y variables of Svg text tags using CSS. This should work as it does with Svg and . However, I am only able to make changes if I directly add the x and y positions in the HTML code. Html: <svg ...

When using AngularJS services to pass data, the data may be lost when the page is refreshed

I'm facing an issue with transferring data from controller A to controller B using a Factory (or a Service) when the user refreshes the browser. I am able to successfully set the data in controller A and retrieve it in controller B, but upon refreshin ...

Learn how to showcase the value of the selected radio button in AngularJS

To show the chosen radio button in the response div, make sure to hide the div if no option is selected. Check out the code below: <body ng-app="QuestionDisplayModule"> <form> <div ng-controller="QuestionDisplayController" ...

Is there a way to detect if JavaScript is disabled using a unique CSS selector?

Does anyone know of a CSS selector that can be used when JavaScript is disabled? I'm not referring to the noscript tag, but specifically in CSS. ...

Anticipating the asynchronous completion of all nested recursive functions

I have a recursive function that makes asynchronous calls, using the results of those calls as arguments for subsequent recursive calls. I am trying to find a way to wait for all recursion levels to complete simultaneously, without any delays at each leve ...

Error in TypeScript: The property "component" is not found on the React MUI MenuItem

I am currently working with the react mui MenuItem component and I am trying to turn a menu item into a link. Here is how I have attempted to achieve this: <MenuItem component={<Link href={`/backend/api/exam/${row.id}/result`} />} className={c ...

The function Array.foreach is not available for type any[]

I'm encountering an issue where when I attempt to use the ".forEach" method for an array, an error message stating that the property 'forEach' does not exist on type 'any[]' is displayed. What steps can I take to resolve this probl ...

Which framework should be used: client-side or server-side?

I am working on a project similar to craiglist, where users can post announcements for everyday items like cars and flats. I have already developed a significant portion of the backend using a RESTful API in three-tier architecture with Java, connecting to ...

Issue found in factory and service dependencies

To retrieve user information, the factory sends a request to the API using ApiRequest.sendRequest: (function() { angular.module('isApp.user', []) .factory('UserProfileFactory', function( $log, ApiRequest, dataUrls ) { // User pr ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

Modify the appearance of the elements dynamically by applying styles from the CSS file without relying on the

In my CSS file, I have the following styles: .myClass { ... } .myClass:focus { ... } Am I able to modify these styles from my code? For instance, can I change the focused style of an input element when a button is pressed? ...