Simon
Simon

Reputation: 47

How to pass data from a child to another a child (nested in Home page) in React?

I'm struggling to figure out how to pass the search term from ChildOne to ChildTwo (which is nested in a page). I hope all the code I provided down below will make it clear. I tried to lift up the state to the App.js component but it didn't work or maybe I didn't do it correctly. I would appreciate any help. Thanks in advance :)

Child 1:

const ChildOne = () => {
  const [searhTerm, setSearchTerm] = useState("");
  
  return(
    <InputContainer>
      <input
        type="text"
        placeholder="Find a recipe"
        value={searchTerm}
        onChange={(e) => {
          setSearchTerm(e.target.value);
        }}
      />
       <SearchIcon />
    </InputContainer>
  )
}

Child 2:

const ChildTwo = () => {
  
 // I want to pass the searchTerm to be used in a fetch request in this component 
  const apiURL = `'url' + {searchTerm}`;
  
  return(
    ...
  )
}

App.js

function App(){

  return(
    <>
      <ChildOne/>
      <Switch>
        <Route path="/" exact component={Home}/>
      <Switch/>
    </>
  )
}

Home.js:

const Home = () => {
  return (
    <>
      <ChildTwo />
    </>
  );
};

Upvotes: 0

Views: 265

Answers (1)

Alireza Barzegar
Alireza Barzegar

Reputation: 61

there is several way to do that... I suggest you use Context Api. if you don't want to use Context Api or State management

see this example

enter link description here

import { useState } from "react";
import {
  Route,
  Switch,
  BrowserRouter as Router,
  RouterProps
} from "react-router-dom";
import ChildOne from "./ChildOne";
import Home from "./Home";

function App() {
  const [value, setValue] = useState("");
  return (
    <>
      <ChildOne setValue={setValue} />
      <Router>
        <Switch>
          <Route path="/" exact>
            <Home value={value} />
          </Route>
        </Switch>
      </Router>
    </>
  );
}

export default App;

Upvotes: 1

Related Questions