Home > Enterprise >  how do i pass a the input value of the textfield from some component to another component in reactjs
how do i pass a the input value of the textfield from some component to another component in reactjs

Time:10-18

I am trying to pass the value of the text area from some component in reactjs to be used in another react component. the component value is stored in the first component in a useState hook so I want to access it in another component and run map() function around it . Is this possible in reactjs ? I don't want to put the whole thing in app.js because that is just plain HTML which I don't want. I want to use reactjs function components instead ?

first component:

import React, { useState, useRef, useEffect } from "react";

function Firstcomp() {
  const [quotes, setQuotes] = useState(["hi there", "greetings"]);
  const reference = useRef();

  function sub(event) {
    event.preventDefault();
    setQuotes((old) => [reference.current.value, ...old]);
    console.log(quotes);

    return;
  }

  return (
    <>
      <div>
        <div>
          <div>
            <h4>jon snow</h4>
          </div>

          <form onSubmit={sub}>
            <textarea
              type="textarea"
              ref={reference}
              placeholder="Type your tweet..."
            />
            <button type="submit">Tweet</button>
          </form>
          {quotes.map((item) => (
            <li key={item}>{item}</li>
          ))}
          {/* we can use card display taking item as prop where it 
            will do the job of filling the <p> in card entry */}
        </div>
      </div>
    </>
  );
}
export default Firstcomp;

second component

import React from "react";

function SecondComp(props) {
  return (
    <div>
      <p>{props.message}</p>
    </div>
  );
}
export default Secondcomp;

CodePudding user response:

You can pass the message to SecondComp as a prop with:

{
  quotes.map((item) => <SecondComp key={item} message={item} />);
}

CodePudding user response:

Use a global management state like Recoil, Redux ot Context

  • Related