1 | initial version |
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>;
}