Home > Back-end >  How can I send the data to the parent component by click on the button in React?
How can I send the data to the parent component by click on the button in React?

Time:11-04

My question is how can I send the input value to the parent component by clicking on the button? Because now if I type something in the input it shanges the value instantly, I want it to do after I click on the button.

Currently I am using that method:

const FormInput = ({setIpAddress}) => {     
    return (
        <div className="formInput">
            <form className="form_container" onSubmit={e => {e.preventDefault();}}>
                <input type="text" id="input" onChange={(e) => setIpAddress(e.target.value)} required={true} placeholder="Search for any IP address or domain"/>
                <button type="submit" className="input_btn">
                    <img src={arrow} alt="arrow"/>
                </button>
            </form>
        </div>
    );
};

export default FormInput

CodePudding user response:

You can pass an onClick callback function to the child component. When this function is called it will trigger a rerender in the child.

Example:

Parent:

const handleClick = (value) => {
  //set the state here
}

<ChildComponent onClick={handleClick} />

Child:

 <button type="submit" className="input_btn" onClick={(value) => props.onClick?.(value)}>

In your case you need to get rid of the onChange in your input tag:

parents:


function App() {
  const [ipAddress, setIpAddress] = useState("");

  const url = `${BASE_URL}apiKey=${process.env.REACT_APP_API_KEY}&ipAddress=${ipAddress}`;

  useEffect(() => {
    try {
      const getData = async () => {
        axios.get(url).then((respone) => {
          setIpAddress(respone.data.ip);
        });
      };

      getData();
    } catch (error) {
      console.trace(error);
    }
  }, [url]);

const handleClick = (event) => {
  setIpAddress(event.target.value)
}

  return (
    <div className="App">
      <SearchSection onClick={handleClick} />
    </div>
  );
}

const SearchSection = ({onClick}) => {
    return (
        <div className="search_container">
            <h1 className="search_heading">IP Address Tracker</h1>   
            
            <FormInput onClick={onClick}/>
        </div>
    );
};

Child

const FormInput = ({onClick}) => {     
    return (
        <div className="formInput">
            <form className="form_container" onSubmit={e => {e.preventDefault();}}>
                <input type="text" id="input" required={true} placeholder="Search for any IP address or domain"/>
                <button type="submit" className="input_btn" onClick={(e) => onClick(e}>
                    <img src={arrow} alt="arrow"/>
                </button>
            </form>
        </div>
    );
};

CodePudding user response:

Thank you for your answer, but I don't really get it, bcs my parent component has no paramter, sorry I am new in react.

This is my parent component where I am fetching the data and I want to update the ipAdress when I click on the button which is in the FormInput component. So the SearchSection is the parent of the FormInput.

function App() {
  const [ipAddress, setIpAddress] = useState("");

  const url = `${BASE_URL}apiKey=${process.env.REACT_APP_API_KEY}&ipAddress=${ipAddress}`;

  useEffect(() => {
      const getData = async () => {
        axios.get(url).then((respone) => {
          setIpAddress(respone.data.ip)
          ... 
          
      getData();
  }, [url]);

  return (
    <div className="App">
      <SearchSection setIpAddress={setIpAddress} />
    </div>
  );
}

CodePudding user response:

I hope it's enough :)

const SearchSection = ({setIpAddress}) => {
    return (
        <div className="search_container">
            <h1 className="search_heading">IP Address Tracker</h1>   
            
            <FormInput setIpAddress={setIpAddress}/>
        </div>
    );
};

function App() {
  const [ipAddress, setIpAddress] = useState("");

  const url = `${BASE_URL}apiKey=${process.env.REACT_APP_API_KEY}&ipAddress=${ipAddress}`;

  useEffect(() => {
    try {
      const getData = async () => {
        axios.get(url).then((respone) => {
          setIpAddress(respone.data.ip);
        });
      };

      getData();
    } catch (error) {
      console.trace(error);
    }
  }, [url]);

  return (
    <div className="App">
      <SearchSection setIpAddress={setIpAddress} />
    </div>
  );
}

  • Related