Denver Dang
Denver Dang

Reputation: 2615

Input value is None from child component using useRef

I have a parent component that has something like:

import React, { useRef } from "react";

const Parent= () => {

  inputRef = useRef(null)
  
  const returnObjects = {
      inputVal: [],

  }; 

  const [data, setData] = useState(returnObjects);

  function fetchData(e?: any) {
    e?.preventDefault();
    POST("/api", {
      input: inputRef?.current?.value,
    }).then(async (response) => {
      const json = await response.json();
      setData({
        inputVal: json.inputVal,
      });
    });
  }

  return (
    <>
        <form onSubmit={fetchData}>
            <Child ref={inputRef} />
            <button type="submit" />
        </form>
        
        
    </>
  );
};

export default Parent;

And a child component like this:

type Props = {
  ref?: any;
};

const Child= ({ value, ref }: Props) => {
  return (
    <>
        <input type="number" ref={ref} />
    </>
  );
};

export default Child;

Now, the idea is when I type something in the Child / input field, I would like to send that value to the fetchData function, which then uses this value in the back-end giving something back.

However, when doing this I just get None from the input field. What am I missing here ?

Upvotes: 0

Views: 572

Answers (1)

Ahmad
Ahmad

Reputation: 1479

Here you have to pass the ref in form tag and call the function on Button

<form ref={inputRef}>
  <Child />
  <button onClick={fetchData} />
</form>

In child component you have to give the just name attribute as you can see the below code

type Props = {
  ref?: any;
};

const Child= ({ value, ref }: Props) => {
  return (
    <>
        <input name="inputValue" />
    </>
  );
};

export default Child;

you can get the value this way in function

function fetchData(e?: any) {
    e?.preventDefault();
    POST("/api", {
      input: inputRef.current['inputValue'].value,
    }).then(async (response) => {
      const json = await response.json();
      setData({
        inputVal: json.inputVal,
      });
    });
  }

Upvotes: 1

Related Questions