Why is my React Native component not getting the props it needs?

Transitioning from my experience with React, I initially believed that passing props worked the same way, but it turns out that's not the case?

Currently, I am working on a login form where I want to differentiate between the styling of the sign in and sign up buttons.

Within my login form component, I have implemented the following method:

   renderButton (type, text) {
        if (this.state.loading) {
            return <Spinner size="small" />;
        }

        let btnColors = {
            bgColor: colors.whiteText,
            textColor: colors.primaryTeal
        };

        if (type === "signUp") {
            btnColors.bgColor = colors.whiteText;
            btnColors.textColor =  colors.primaryTeal;

        } else if (type === "logIn") {
            btnColors.bgColor = colors.darkTeal;
            btnColors.textColor = colors.whiteText;
        }
        return (
            <Button colors={btnColors} onPress={this.onButtonPress.bind(this)}>
                {text}
            </Button>
        );
    }

Called in the Render method like this:

{this.renderButton("signUp", "SIGN UP")}

The Button component's code is as follows:

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


const Button = ({colors, onPress, children }) => {

    const styles =  StyleSheet.create({
        textStyle: {
            alignSelf: 'center',
            color: colors.textColor,
            fontSize: 16,
            fontWeight: '900',
            paddingTop: 10,
            paddingBottom: 10,
        },
        buttonStyle: {
            flex: 1,
            backgroundColor: colors.bgColor,
            borderRadius: 50
        },
    });

      return (
            <TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
              <Text style={styles.textStyle}>
                  {children}
              </Text>
            </TouchableOpacity>
      );
};


export { Button };

The encountered error is:

undefined is not an object (evaluating 'colors.textColor')

Why is it not working, and what is the correct way to conditionally pass props as an object for styling purposes?

Answer №1

To resolve the issue, consider converting the component from a functional component to a class component. Alternatively, you can utilize the fat arrow syntax for a concise solution:

const Greetings = ({name}) => ( <div>{`Hello ${name}`}</div>);

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

The PHP-generated table is not being appended to the specified div with jQuery

I am currently working on developing a webpage that displays live forex rates to users. I am pulling the values from a feed and echoing them into a table. My goal now is to use jQuery to show this table to the user. The issue I am facing is that when I tr ...

Javascript error specific to Internet Explorer. Can't retrieve the value of the property 'childNodes'

After removing the header information from the XML file, the issue was resolved. Internet Explorer did not handle it well but Firefox and Chrome worked fine. An error occurred when trying to sort nodes in IE: SCRIPT5007: Unable to get value of the proper ...

Key press event not firing as expected

<multiselect v-model="value" :options="websites" label="url" track-by="url" :allow-empty="false" class="header-select mr-3" v-on:keyup.enter="submit"></multiselect> My requi ...

Anticipate feedback from Python script in Node.js

I have developed a website using nodejs and express, but I am facing an issue with integrating a python script for face recognition. The problem lies in the fact that when I invoke this script from nodejs using child-process, it takes around 10 to 20 secon ...

The JSON retrocycle function selectively converts certain references only

I have an array of objects with some cyclic references. To handle this, I used JSON.decycle when sending the object via JSON and JSON.retrocycle on the receiving end. For example: var refactor_data = JSON.retrocycle(JSON.parse(event.data)); The issue is ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

Import a JavaScript file with beneficial test functions for selenium testing

Utilizing the runScript command in selenium has proven to be incredibly helpful for me. I've been using it to calculate values within a table and then store the result like so: <tr> <td>runScript</td> <td>var cumulativ ...

Error: The function Object.entries is not defined

Why does this error persist every time I attempt to start my Node.js/Express server? Does this issue relate to the latest ES7 standards? What requirements must be met in order to run an application utilizing these advanced functionalities? ...

Inquiry into AngularJS data binding

Just dipping my toes into the world of Angular today. Found a tutorial at Angular JS in 30 mins This little project involves setting up basic databinding in Angular. The code features an input box that updates with whatever is typed next to it. As someone ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

Converting a JavaScript IIFE library into a React Component

Hello, I am currently in the process of learning React JS and there are two JavaScript files that I am working on: Polyfill.js -> hosted on github CustomNavbar.js -> created by me Here is the structure of polyfill.js: export default (function(win ...

Struggling with showcasing Trips in my React Native project and looking for guidance on the best approach to implement it beautifully

API: app.get('/trip', async (req, res) => { try { const employeeId = req.query.user; const empId = new ObjectID(employeeId); // Retrieving Fleet associated with the driver's ID const fleet = await Fleet.findOne({ a ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

Access various results from a jQuery function

Is there a way to efficiently extract the values of petKeys and employeeKey using the jQuery functions provided below? var whenSelectDateFromCalendar = function () { initKeyValues(); petKeys = ? employeeKey = ? }; var initKeyValues = function ...

Adjust hover effects based on true conditions

Currently working on a web app using HTML, CSS, JavaScript, and AngularJS. Progress so far includes a clickable box that triggers a javascript function to display more boxes upon click using ng-click. <div ng-click="!(clickEnabled)||myFunction(app)" cl ...

Retrieving text data in Controller by utilizing jQuery AJAX request

Text box and button for input <input type="text" class="form-control" name="ClaimNumber" placeholder="Enter a claim number" id="ClaimNumber" /> <button class="btn btnNormal" type="submit" id="btnSearch"> ...

Enhance D3 Version 6 Stacked Bar Chart with Spacing and Interactive Features

My bar chart lacks the spacing between bars that I intended to achieve, and the interactive tooltip doesn't show up when hovering over the bars. I could use some assistance with this. The purpose is to display the value of a specific color when hoveri ...

Conceal any ng-repeat elements that do not contain corresponding grandchildren within two levels of nested ng-repeats

Apologies for the enigmatic title, but the issue at hand is quite cryptic ¯\_(ツ)_/¯ I'm dealing with a complex problem involving 3 nested ng-repeats to display Google Analytics' account structure. Within this structure are multiple acco ...