Home > OS >  React cannot pass props to parent component
React cannot pass props to parent component

Time:01-02

GOAL: Give data to App comp from Register comp, then from App comp to Chat comp Register --> App --> Chat Additional info: Register is taking a username and then passing it to Chat comp to render as username

Or should I just pass the value to url params and then get it? The answers I looked up were suggesting creating redux or were from class components

import Chat from "./components/chat";
import Register from "./components/register";
import { BrowserRouter, Route, Routes } from "react-router-dom";
function App(props) {
  console.log(props);
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Register />}>
          <Route
            path="chat"
            element={(props) => <Chat {...props} data={true} />}
          />
        </Route>
        <Route
          path="*"
          element={
            <main style={{ padding: "1rem" }}>
              <p>404 :)</p>
            </main>
          }
        />
      </Routes>
    </BrowserRouter>
  );
}

Register component:

import { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function Register() {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const generatedName = `user#${Math.floor(Math.random() * 1000000   1)}`;
  const handleSubmit = () => {
    if (name === "") {
      setName(generatedName);
    }

    navigate("/chat", { replace: true });
    HERE I WANT TO RETURN THE DATA TO PARENT//return "hello parent";
  };
  return (
    <div>
      Enter username:{" "}
      <input
        placeholder={generatedName}
        onChange={(e) => setName(e.target.value)}
      ></input>
      <button onClick={() => handleSubmit()}>enter</button>
    </div>
  );
}

CodePudding user response:

You can set up a data state in your app component using a useState hook and pass a reference to a setter function which modifies your data and set it to a value and pass both of them to the Register component. Also, pass the data to your chat component as you would need it. You can try like below,

In App component,

...

function App(props) {
  const [data,setData] = useState('');

  const myDataSetterFunction = (dataToBeSet) => {
     setData(dataToBeSet);
  }

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Register intialData={data} myDataSetterFunction={myDataSetterFunction}   />}>


          <Route
            path="chat"
            element={(props) => <Chat dataToBeSupplied={data} {...props} data={true} />}
          />
        </Route>
        <Route

....

The Register component can modify the data and use the passed setter Function to modify the state of the hook. As soon as the data is modified there will be a re-render triggered which will pass the data or you can pass the data only if the data changes from the initial value to be more safer.

Inside the Register.js use the props to call the function passed to set the data inside the app doing something like this.

props.myDataSetterFunction( ...dataToBeReturned... );

Also, Remember to make sure the data has some value before passing it to the chat and using it.

CodePudding user response:

In here, you can use queryParams when you switch to new component:

navigate({ pathname: '/chat', search: '?message=hello parent', });

In React we cannot directly pass props from child to parent. you can pass a function as a prop from parent component to child component, then call that function in child component.

CodePudding user response:

If Register comp took the input name then render Chat comp. Not sure if I needed this react-router-dom thing

function Register() {
  const navigate = useNavigate();
  const [passedUsername, setForPassedUsername] = useState(false);
  const [name, setName] = useState("");
  const generatedName = `user#${Math.floor(Math.random() * 1000000   1)}`;
  const handleSubmit = () => {
    if (name === "") {
      setName(generatedName);
    }
    setForPassedUsername(true);
    navigate("/chat", { replace: true });
    return "hello parent";
  };
  return (
    <div>
      {passedUsername ? (
        <Chat data={name}></Chat>
      ) : (
        <div>
          Enter username:{" "}
          <input
            placeholder={generatedName}
            onChange={(e) => setName(e.target.value)}
          ></input>
          <button onClick={() => handleSubmit()}>enter</button>
        </div>
      )}
    </div>
  );
}
  • Related