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

Is there a way to reposition the arrows in this Bootstrap 5 accordion to appear ahead of the text?

Here's an example from Bootstrap 5 web page that I've been working with (https://getbootstrap.com/docs/5.0/components/accordion/). My query pertains to positioning the arrows before the text in the accordion items. Despite attempting various appr ...

Inquiring about the intricacies of using Regular Expressions in

Can anyone provide a regex that only allows the characters 0-9, a-z, A-Z, hyphen, question mark, and "/" slash, with a character length between 5 to 15? I attempted the following approach, but it did not yield the desired result: var reg3 = /^([a-zA-Z0-9? ...

Tips for How to Put a Delay on Ajax Requests and Display a Progress Bar During Loading

I am using checkboxes in the sidebar. When a user selects a checkbox from the sidebar, it displays the post normally. Is there a way to add a progress bar to delay the Ajax result? This is my Ajax code: <script> jQuery(document).ready(function($){ ...

How to eliminate the hashtag from the slug while referencing an element by its id in Next.js

Is there a way to eliminate the # from the URL when referencing an element by its id (changing domain.com/#contact to domain.com/contact)? For example, if you click this link: <Link href="about"><a>Contact</a></Link>, the ...

I am considering open-sourcing my website, but I am concerned about the file containing my database credentials

I developed a NextJS website that I am considering open sourcing, but I have sensitive credentials stored in a .env file for my database access. While I don't anticipate major issues if these credentials were exposed to the public, I prefer not to tak ...

Identify and react to an unexpected termination of an ajax upload process

My ajax uploading code can determine if a file was successfully uploaded only after the upload has completed. If the upload is terminated before completion, no data is returned. Is there a way to detect when an upload is unexpectedly terminated and alert t ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Why aren't my messages showing up once I exit the textbox on my website?

After writing various functions to compare two passwords, I encountered an issue. My goal was for the message "The passwords match" or "Please enter your password again because the two passwords don't match" to be displayed when clicking out of the "v ...

Error: Unable to find axios module

screenshot of browser developer tool - network I have embedded the script in my base.pug file script(scr='https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js') Upon loading the page and inspecting the browser developer tool > n ...

Is it possible to customize bootstrap classes for a unique bootstrap css design?

In my MVC4 project, I faced a situation where I had a global.css class with some classes that conflicted with Bootstrap after adding it. To resolve this, I created a new file called bootstrap_migration.css. In this file, I prefixed the Bootstrap classes wi ...

The "users" property or method has not been defined in Vue.js applications

During the development of my Vue.js shopping cart, I encountered an issue where I wanted to display the username in a label after the user provided correct information. However, I received the following error in Google Chrome: vue.js:634 [Vue warn]: Prope ...

Changing the hidden input value to the data-id of a selected <a> element

I've set up a form with a dropdown menu and subdropdowns, generated using a foreach loop through a @Model. When I click on one of the options, I want the value of my hidden input field to match the data-id of the clicked item. This is what I have in ...

Is there a way to make a TABLE expand to match the height of its surrounding element? (or, tackling sluggishness in IE with JavaScript)

I am facing a challenge with a web page where I have a table nested inside of a TD tag. Despite the unconventional approach, I need to ensure that the height of the nested table matches the height of the TD cell containing it upon page load. Currently, I a ...

Developing an if-else statement to showcase a different div depending on the URL

Having trouble with an if/else statement to display one div or another based on the URL: No matter what I try, only "Div 1" keeps showing. Here's my code snippet: <script> if (window.location.href.indexOf("pink") > -1) { document.getElemen ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

"Can someone guide me on where to place the JavaScript code within this Bootstrap snippet when working with CakePHP

I'm currently delving into CakePHP and am eager to incorporate this Bootstrap code snippet from onto my website. I've successfully added the HTML to the .ctp file in the Pages directory and styled it with custom.less, but I hit a roadblock when ...

Utilizing jQuery to efficiently chunk JSON data through AJAX calls

Is there a way to efficiently handle the retrieval of large amounts of JSON data through an ajax request? I am looking for a jQuery or JavaScript function that can assist with "chunking" the data. For example, I would like the ability to continuously rece ...

Pick the item when the checkbox is selected

I am currently attempting to toggle the visibility of a select element based on whether a checkbox is checked or not, but it doesn't seem to be working as expected. My desired functionality is for the select element to be hidden upon page load and th ...

I am looking to implement a straightforward drag-and-drop feature using jQuery

Is it possible to drag and select 4 buttons in a browser, similar to how you would do on Windows, using jQuery locally? ...