Communication between Stateless Functional Components
suggest changeIn this example we will make use of Redux and React Redux modules to handle our application state and automatically re-render our functional components, and of course React and ReactDOM.
You can check out the completed demo here.
In the example below we have three different components and one connected component:
- UserInputForm: This component displays an input field, and when the field value changes it calls the
inputChangemethod onprops(which is provided by the parent component). If data is provided as well, it displays that in the input field. - UserDashboard: This component displays a simple message and also nests the
UserInputFormcomponent. It passes aninputChangemethod toUserInputForm, andUserInputFormin turn uses that method to communicate with the parent component. - UserDashboardConnected: This component wraps
UserDashboardwith theReactReduxconnectmethod. This makes it easier to manage the component state and update the component when that state changes. - App: This component just renders the
UserDashboardConnectedcomponent.
const UserInputForm = (props) => {
let handleSubmit = (e) => {
e.preventDefault();
}
return(
<form action="" onSubmit={handleSubmit}>
<label htmlFor="name">Please enter your name</label>
<br />
<input type="text" id="name" defaultValue={props.data.name || ''} onChange={ props.inputChange } />
</form>
)
}
const UserDashboard = (props) => {
let inputChangeHandler = (event) => {
props.updateName(event.target.value);
}
return(
<div>
<h1>Hi { props.user.name || 'User' }</h1>
<UserInputForm data={props.user} inputChange={inputChangeHandler} />
</div>
)
}
const mapStateToProps = (state) => {
return {
user: state
};
}
const mapDispatchToProps = (dispatch) => {
return {
updateName: (data) => dispatch( Action.updateName(data) ),
};
};
const { connect, Provider } = ReactRedux;
const UserDashboardConnected = connect(
mapStateToProps,
mapDispatchToProps
)(UserDashboard);
const App = (props) => {
return(
<div>
<h1>Communication between Stateless Functional Components</h1>
<UserDashboardConnected />
</div>
)
}
const user = (state={name: 'John'}, action) => {
switch (action.type) {
case 'UPDATE_NAME':
return Object.assign( {}, state, {name: action.payload} );
default:
return state;
}
};
const { createStore } = Redux;
const store = createStore(user);
const Action = {
updateName: (data) => {
return { type : 'UPDATE_NAME', payload: data }
},
}
ReactDOM.render(
<Provider store={ store }>
<App />
</Provider>,
document.getElementById('application')
);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents