Reputation: 1310
I create 2 components: Parent and Child.
Child-component contains the input-field, in which user enter the data. Entering data must be send to redux-store.
class Child extends Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(event) {
// store-logic
}
render() {
return (
<div>
<button onClick={this.handleSubmit}>Search</button>
<input type="text" value="" onClick={this.handleChange}/>
</div>
)
}
}
export default Child
Parent-component:
import store from '/store/configureStore';
class Parent extends Component {
constructor(props) {
super(props)
}
return (
<div className="App">
<Child />
</div>
);
}
ReactDOM.render(
<Provider store={store}>
<Parent />,
</Provider>,
document.getElementById("app")
);
Reducer:
const initialState = {
inputed_data: "value...",
};
export default function update(state = initialState, action) {
switch (action.type) {
case 'INPUT':
return {
...state,
[action.payload.target.name]: action.payload.target.value
};
default:
return state;
}
}
And I cant understand, what I need to add in this code to finally provide sending data from Child-component to store.
Leaning different articles, I come to a conclusion, that I need to use mapStateToProps and connect(). But where I able to use this functions - in Parent or Child?
Upvotes: 1
Views: 1131
Reputation: 2176
In order to save something in store you'll have to use mapDispatchToProps method with connect function
You can connect Parent component and pass dispatcher as a prop to the Child or connect Child component and dispatch action directly from it. It depends on the functionality that you want to provide in the Parent and in the Child components.
Example for child component:
// inside child component code
const handleSubmit = (event) => {
this.props.submitToStore(event);
}
// code to connect Child component
const mapDispatchToProps = (dispatch) => ({
// this will be injected in child component props
submitToStore: (input) => dispatch({ type: 'INPUT', payload: input }),
});
// connect child component to the store
// first argument here is for mapStateToProps but we don't have any so it will be null
export default connect(null, mapDispatchToProps)(Child)
Upvotes: 1