Ask Your Question
4

How can I pass a value from App.js to an element in React JS?

asked 2022-04-05 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-10-26 20:00:00 +0000

djk gravatar image

There are several ways to pass a value from App.js to an element in React JS. Here are some common methods:

  1. Using Props: You can pass values as props to child components. In App.js, you can define a prop and pass it to the child component.

Example:

function App() {
  const myValue = "Hello World";
  return (
    <ChildComponent myProp={myValue} />
  );
}

function ChildComponent(props) {
  return <div>{props.myProp}</div>;
}
  1. Using Context API: The Context API allows you to pass data through the component tree without having to pass props down manually at every level.

Example:

export const MyContext = React.createContext();

function App() {
  const myValue = "Hello World";
  return (
    <MyContext.Provider value={myValue}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

function ChildComponent() {
  const myValue = React.useContext(MyContext);
  return <div>{myValue}</div>;
}
  1. Using State Management Libraries: You can use state management libraries like Redux or MobX to pass values across components.

Example with Redux:

import { createStore } from 'redux';

const initialState = {
  myValue: "Hello World"
};

function reducer(state = initialState, action) {
  switch (action.type) {
    default:
      return state;
  }
}

const store = createStore(reducer);

function App() {
  return (
    <Provider store={store}>
      <ChildComponent />
    </Provider>
  );
}

function ChildComponent(props) {
  const myValue = useSelector(state => state.myValue);
  return <div>{myValue}</div>;
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-05 11:00:00 +0000

Seen: 29 times

Last updated: Oct 26 '22