React functional parent component sharing common onChange functions without redundant code

react pass function as prop to child component
react pass function as prop functional component
react functional components
react call parent function from child
react call function from another component
react hooks
react callback function example
react router

React can pass onChange functions from functional parent to functional child for the child to use to update the parent. But writing the same onChange functions in several Form building components seems redundant - and I'm hoping there's a better way to build forms faster or a more global method of a child calling parent functions WITHOUT the use of classes.

  1. I've attempting to create an external function and importing it on all components that build forms and pass on onChange to a Field component. But after importing them, they do not have automatically have access to the setValue part of the statehook

  2. I tried Context, but you can't send a dynamic, initial state that has all of the field / values for your form so you get an error regarding controlled and uncontrolled inputs

function Episode({ match }) {

   const [formData, setData] = useState(content.form);

   ...retrieve data from API …

   const updateFieldState = e => {
    switch(e.target.type){
     case 'text':
     case 'textarea':
     case 'select-one':
      setValues({
        ...formValues,
        [e.target.id]: e.target.value
      });
      break;
     case "checkbox":
     . . . . . .(you get the idea here)
    }

   return {
   <Form>
     <Field id="item_title" changeHandler={updateFieldState}/>
     <Field id="item_subtitle" changeHandler={updateFieldState}/>
     . . . . . .(custom child component Field that creates an input and adds updateFieldState to its onClick event )
   <Form>
  }
}

As it stands, I would not only need to redundantly add this changeHandler to every field on this form, but I'd have to redundantly rewrite updateFieldState on EVERY component that builds a from like this creating.

Any help, suggestions or tutorials on how to build faster forms without the use of classes would be appreciated.

Have you considered writing a custom hook?

You could have something like

function useFormHandler(initialData) {
  const [formData, setData] = useState(initialData);
  const fieldChangeHandler = e => {
    // actual implementation that uses setData
  }

  return [formData, fieldChangeHandler];
}

function Episode({ match }) {
  const [formData, fieldChangeHandler] = useFormHandler(content.form);
  ...
}

If you want to avoid passing fieldChangeHandler to each field manually, you could pass it to the <Form> component, and rewrite its render method so that it actually forwards the fieldChangeHandler property to its children (or use context).

Passing Functions to Components – React, How do I bind a function to a component instance? There are several ways to make In JavaScript, these two code snippets are not equivalent: obj.method();. The example above was of a functional component. If you’re using a Class component, you will have to bind the onChange event handler to the context of this. Example: Saving an Input Value Inside of State using onChange in a React Component. The final example we’ll explore today is how to store an input’s current value inside of a state value.

I think you are looking for something binding. U can use either bind or curry method. A simple solution could be based on the below answer/example.

const method = (salute, name) => `${salute} ${name}` 
const Mr = method.bind(null, "Mr.")
const Ms = method.bind(null, "Ms.")
Mr("Deepak")//"Mr. Deepak"
Ms("Rina")//"Ms. Rina"

So your case

onChnage.bind(null, "text")
onChnage.bind(null, "textarea")

Clean Code vs. Dirty Code: React Best Practices, Now is your chance to clean it up by removing dead code (zombie code), refactoring, and Writing unit tests is not just a good idea, it's become almost mandatory. Did you remember to change your comments as well to reflect the new logic? In my previous article Function as Child Components Are an  Passing Data from Child to Parent Wait, isn't unidirectional data flow a core design philosophy of react? Well, that is true. And we shouldn't be passing anything up the component tree using the most common method for passing data around, props. However, we can actually design functions in our parent, and pass them down the component

In my opinion, you should create HOC, that consist your updateFieldState logic.

// withFieldFunctions.js
const withFieldFunctions = (WrappedComponent) => {
  const updateFieldState = e => {
    switch(e.target.type){
     case 'text':
     case 'textarea':
     case 'select-one':
      setValues({
        ...formValues,
        [e.target.id]: e.target.value
      });
      break;
     case "checkbox":
     . . . . . .(you get the idea here)
    }
  }

  return <WrappedComponent updateFieldState={updateFieldState} {...this.props} />
}

// SampleFormComponent.js
import withFieldFunction from './withFieldFunctions.js'

const SampleFormComponent = (props) => {
  return (
    <Form>
     <Field id="item_title" changeHandler={props.updateFieldState}/>
     <Field id="item_subtitle" changeHandler={props.updateFieldState}/>
    <Form>
  )
}

return withFieldFunctions(SampleFormComponent)

In that way, you can create a different form and wrap it with withFieldFunctions

Popular Science, IT'S A WORD THAT SIMPLY CANNOT BE AVOIDED WHEN TALKING ABOUT MANY NOTABLE TECHNOLOGIES AND INNOVATIONS. NOT THAT WE'D WANT  React Function Components -- also known as React Functional Components -- are the status quo of writing modern React applications. In the past, there have been various React Component Types , but with the introduction of React Hooks it's possible to write your entire application with just functions as React components.

The Advocate, Events taken for granted today were once part of a cutting-edge journey to a new frontier By Don Romesburg ALICE B. TOKLAS (LEFT) MEETS GERTRUDE  If you need to have access to the parent component in the handler, you also need to bind the function to the component instance (see below). How do I bind a function to a component instance? There are several ways to make sure functions have access to component attributes like this.props and this.state , depending on which syntax and build

Leveling Up With React: Container Components, There is code to follow along with at GitHub, if you like to dive right into code. However, the props and state of a parent component will become just props to their child ComponentA render: function() { return <ComponentB foo={this.state​.foo} Presentational Components should never change the prop data itself. In fact  This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions. You can also use an ES6 class to define a component:

Handling Multiple Inputs with a Single onChange Handler in React , When creating a form with React components, it is common to use an The value of the prop is the handleChange function; It is an event handler. We'll consume them in an adjustment to the handler code: Note that the currently-​selected value is set via the value prop on the parent select element. The child then calls this function at some point and passes it a value that the parent is supposed to react to. We then write the functionality for the parent's reaction inside the parent component. Phew. Let's just write some code! We will write a method in the App component that receives a zipcode and saves it in it's own state.