简体   繁体   中英

How to get value of a component to another component

I am creating a Project where I need to get value of a component state value to another component.

How can I get the value?

Information

  1. Both are functional component.
  2. I need to send data from A (state) to B(state).
  3. A state data are set from react dropdown menu.Which is a button.
  4. I don't use Link or Route to A dropdown that's why I can't get it with useParams()
  5. I need to set value in B component which will fetch data with passing language.
  6. I have import all needed things & don't have any warnings & error.

Code of component A

  1. Send value from this language state to B
const A = () => {
    const [language, setLanguage] = useState('en');
    
    return (
        <Navbar expand="xl" bg='light' expand={false}>
            <Container>
                <DropdownButton id="dropdown-basic-button" title={<MdOutlineLanguage />}>
                    <Dropdown.Item as="button" onClick={() => setLanguage('en')}>English</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('ar')}>العربية</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('bn')}>বাংলা</Dropdown.Item>
                </DropdownButton>
            </Container>
        </Navbar>
    )
};

export default A

Code of Component B

  1. I need to get here A state value & set it to B state. Then pass to useGetDataQuery & fetch data.
const B = () => {
    let [language, setLanguage] = useState('en')
    const { data } = useGetDataQuery({language })
    
    return (
        <>
            
        </>
    )
}
export default B

Redux Section

I'm using readux & @reduxjs/toolkit to store fetch data. Can I store my language data to here. Than how can get to from anywhere of my component.

  1. react-rotuer-dom v6
export default configureStore({
    reducer: {
        [dataOne.reducerPath]: dataOne.reducer,
        [data2.reducerPath]: dataTwo.reducer,
    },
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: false
        }).concat([dataOne.middleware, dataTwo.middleware]),

})

Maybe instead of using useState , you can use a global state by using useContext because I think your language will be use on several places as request body and of course to edit the state value, you can combine it with useReducer .

// UPDATE

working code: https://codesandbox.io/s/sleepy-monad-21wnc

MyContext

import { useReducer, useContext, createContext } from "react";

const initialValue = {
  language: "id"
  // other: "value",
};

const AppContext = createContext(initialValue);

const AppReducer = (state, action) => {
  switch (action.type) {
    case "CHANGE_LANGUAGE":
      return {
        ...state,
        ...action.payload
      };
    default:
      return state;
  }
};

const MyContext = ({ children }) => {
  const [state, dispatch] = useReducer(AppReducer, initialValue);
  return (
    <AppContext.Provider value={[state, dispatch]}>
      {children}
    </AppContext.Provider>
  );
};

export const useAppContext = () => useContext(AppContext);
export default MyContext;

this is the context and reducer component later on use in App.js

App.js

import A from "./A";
import B from "./B";
import MyContext from "./MyContext";
import "./styles.css";

export default function App() {
  return (
    <MyContext>
      <div className="App">
        <A />
        <B />
      </div>
    </MyContext>
  );
}

A.js

import { useAppContext } from "./MyContext";

const A = () => {
  const [globalState, dispatch] = useAppContext();

  const onChange = (e) => {
    dispatch({
      type: "CHANGE_LANGUAGE",
      payload: {
        [e.target.name]: e.target.value
      }
    });
  };

  return (
    <>
      <p>Start Of Component A </p>
      <input value={globalState.language} name="language" onChange={onChange} />
      <p>End Of Component A </p>
    </>
  );
};

export default A;

B.js

import { useAppContext } from "./MyContext";

const B = () => {
  const [globalState, dispatch] = useAppContext();

  return (
    <>
      <p>Start Of Component B </p>
      <h2>Language Val : {globalState.language}</h2>
      <p>End Of Component B </p>
    </>
  );
};

export default B;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM