There are several ways to pass a value from App.js to an element in React JS. Here are some common methods:
Example:
function App() {
const myValue = "Hello World";
return (
<ChildComponent myProp={myValue} />
);
}
function ChildComponent(props) {
return <div>{props.myProp}</div>;
}
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>;
}
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>;
}
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
Asked: 2022-04-05 11:00:00 +0000
Seen: 11 times
Last updated: Oct 26 '22