3

I have created a field array with file input and a text field. Everything seems to works fine but when I try to upload a small image or typing something in the textfield, a Type error pops up with "onChange is not a function" message. How do I fix this error?

I have uploaded the code to codesandbox: https://codesandbox.io/s/cool-wildflower-6jlcl?file=/src/App.js

jch02140
  • 45
  • 1
  • 6
  • 1
    ` onChange({text:event.target.value})}/>` you are calling the onChange function but you never declared it. What exactly do you want to do with the input value? – Cornel Raiu Jul 02 '21 at 01:08

3 Answers3

3

Your whole code works as expected, the error you are getting is because onChange function is not declared. You are expecting it from the render prop of the Controller component but you are not getting it the right way.

Line 71

render={({ onChange }) => /** rest */ }

should be

render={({ field: { onChange } }) => /** rest */ }

You can see an example of how this is done in react hook form docs

Kerosz
  • 168
  • 6
0

well, Firstly you can't name the function as onChange as the default onChange already defined, secondly you never defined the function.

  const handleChange = (value) => console.log("onchange ", value);

then

<Controller
                  control={control}
                  name={`files.${index}.description`}
                  render={({ onChange }) => (
                    <input
                      style={{ border: "1px solid blue" }}
                      placeholder={"describe your file here"}
                      onChange={(event) =>
                        handleChange({ text: event.target.value }) // calling the handleChange function
                      }
                    />

I think it should work

Sifat Amin
  • 1,091
  • 6
  • 15
0

You are calling the onChange function but you never declared it.

1. The input field

From what I can see you have to only do 2 small changes to get the input working correctly:

  1. Declare another state variable:

const [input, setInput] = useState("");

  1. Change your input onChange parameter to:

onChange="event => setInput(event.target.value)"

This should make the text input work.

2. The file input field

For the file input, make sure you read this

Because its value is read-only, it is an uncontrolled component in React. [...] You should use the File API to interact with the files.

Some more docs: https://reactjs.org/docs/forms.html#controlled-components

Forms as functional components with react

https://rangle.io/blog/simplifying-controlled-inputs-with-hooks/

Cornel Raiu
  • 2,758
  • 3
  • 22
  • 31