React Redux Tutorial
Accessing child component from parent component in react js
React redux is used to manage the state between two pages.
Example:
Consider we are registering a user, Registration is one of the component which is going to render in the parent component where data is saving.
Child:
Parent:
npm install redux
npm install react-redux
Step 1:
actions.js
creating actions
export const setChildProps = (data) => ({
type: 'SET_CHILD_PROPS',
payload: data,
});
Step 2:
reducers.js
creating reducers
const initialState = {
childProps: [],
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'SET_CHILD_PROPS':
return {
...state,
childProps: {
...state.childProps,
...action.payload,
},
};
default:
return state;
}
};
export default rootReducer;
Step 3:
store.js
creating store
// store.js
import { legacy_createStore as createStore } from 'redux';
import rootReducer from './reducer';
const store = createStore(rootReducer);
export default store;
Step 4:
creating child component for data collection from user
import { connect } from 'react-redux';
import { setChildProps } from './actions';
const ChildComponent = ({ setChildProps }) => {
const handleChange = (e) => {
const { name, value } = e.target;
setChildProps({ [name]: value });
};
return (
<div>
<h1>User Registraion (Child Component)</h1>
First Name: <input type="text" name="firstName" placeholder="First Name"
onChange={handleChange} />
<br />
Last Name: <input type="text" name="lastName" placeholder="Last Name"
onChange={handleChange} />
</div>
);
};
const mapDispatchToProps = {
setChildProps,
};
export default connect(null, mapDispatchToProps)(ChildComponent);
Step 5:
creating parent component for data save
// ParentComponent.js
import React, { useState } from 'react';
import { connect } from 'react-redux';
import ChildComponent from './ChildComponent';
const ParentComponent = ({ childProps }) => {
const onSave = (e) => {
alert(childProps.firstName);
}
return (<div>
<ChildComponent />
<br />
<hr />
<h1>Parent Component</h1>
<p>FirstName: {childProps.firstName} </p>
<p>LastName: {childProps.lastName}</p>
<input type='button' value="Save" onClick={onSave}
style={{paddingLeft:"20px",paddingRight:"20px",paddingTop:"5px"
,paddingBottom:"5px",fontWeight:"bold"}} />
</div>)
};
const mapStateToProps = (state) => ({
childProps: state.childProps,
});
export default connect(mapStateToProps)(ParentComponent);
Step 6:
app.js
importing store and add ParentComponent inside Provider
import './App.css';
import ParentComponent from './ParentComponent';
import { Provider } from 'react-redux';
import store from './store';
function App() {
return (
<div className="App">
<Provider store={store}>
<ParentComponent />
</Provider>
</div>
);
}
export default App;