What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to switch seamlessly between the two as wrappers. Unfortunately, I haven't quite figured out how to accomplish this yet. Below is a snippet from the class:

const FormikControl = (props) => {
  const {
    name,
    type,
    label,
    disabled,
    fullWidth,
    isDynamic, // Field (true) or FastField
  } = props;
  const classes = useStyles();

  const inputProps = {};

  switch (type) {
    case 'text':
      return (
        <>
          <ComplexField name={name} isDynamic={isDynamic} {...props}> // intended to be the wrapper that switches
            {({ field }) => {
              return (
                <TextField
                  {...field}
                  variant="standard"
                  label={label}
                  fullWidth={fullWidth}
                  disabled={disabled}
                  InputLabelProps={{
                    shrink: true,
                  }}
                  InputProps={inputProps}
                  value={field.value || ''}
                />
              );
            }}
          </ComplexField>
          <ErrorMessage error name={name} component={FormHelperText} />
        </>
      ); 

ComplexField is supposed to act as the flexible wrapper, capable of switching between Field and FastField based on "isDynamic". My attempt at achieving this was:

const ComplexField = ({ name, children, isDynamic, ...props }) => {
  return isDynamic ? (
    <Field name={name} props={props}>{({ field }) => children({ ...props, field })}</Field>
  ) : (
    <FastField name={name} props={props}>{({ field }) => children({ ...props, field })}</FastField>
  );
};

Unfortunately, it didn't work :(

Answer №1

<ComplexField name={name}>

The prop "isDynamic" is missing in your code. Is this intentional? Without it, the functionality may not work as expected.

<ComplexField name={name} isDynamic={isDynamic}>

If you're looking for a better approach, check out this article on Conditionally render react 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

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Rearrange HTML list items automatically according to changes in numeric sort order

I am working on a web page that features a dynamic ranked list. The items in the list are assigned a specific rank order number which changes based on user interactions elsewhere on the page. I have been exploring different options to automatically reorgan ...

javascript issue with fetching data from URL using the GET method

Here is my attempt to fetch a JSON file from a server using asynchronous JavaScript promises. I am experiencing an issue where the result is undefined when using a specific URL, but it works when I use a different URL. Below is the working code with a dif ...

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Issue with Website Rendering: Safari 4 exhibits display glitch showing temporary content before showing a blank white screen

Currently, I'm in the process of developing a specialized rails application. However, there seems to be an unusual rendering error that has been reported by Safari 4 users. It's quite peculiar because the page appears briefly but quickly disappea ...

AngularJS: Struggling to Set Up Controller

I recently started my journey with AngularJS a few days back, and I've encountered this frustrating issue. Every time I run into this error: Error: ng:areq Bad Argument Argument 'NewStudentCtrl' is not a function, got undefined All my ot ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Conditionally validate fields based on a different field using Yup and Formik

I am facing an issue with validation. I would like to set a rule that allows selecting both the start_date and end_date only if the access value is 1. Otherwise, if the access value is not 1, then only today's date should be selectable. Check out the ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

Prevent the button from being enabled until the file input is updated

I want to create a form with an input file for uploading photos, but I need the submit button to be disabled until the input file has a value. Additionally, there are other validations that will also disable the button. Here is the structure of my HTML fi ...

I am looking to efficiently store various pieces of data in a database by utilizing a singular variable through JS, PHP, and AJAX for streamlined processing and management

I am not very familiar with the technical jargon in programming, so please bear with me if my question is a bit unclear. To provide more clarity, I have shared the code that I have already written. I will elaborate on the issue after presenting the code: ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Structure of a GraphQL project

What is the most effective way to organize a graphQL project on the server side? Here is my current project structure: src config models setup schema queries index userQuery resolvers index userRes ...