Showing posts with label setState. Show all posts
Showing posts with label setState. Show all posts

Friday, August 14, 2020

mapDispatchToProps in Redux

mapDispatchToProps function is used to dispatch actions to the store in a react-redux application.
To dispatch an action to the store we need to call store.dispatch. In a React Redux application the React component does not have access to the store directly hence it cannot call store.dispatch. The connect method which connects react and redux provides the mapDispatchToProps through which react components can dispatch actions.

If mapDispatchToProps is not defined in connect, there is another way to dispatch actions from React components. In this case props.dispatch is passed to the component and using this we can dispatch actions to the store.

Tuesday, August 7, 2018

Event handler example in React

Event handlers are used to handle various events arising from controls in React components. Event handlers are functions in react component, event handlers are bound to events in React components in the constructor or the component using bind()

this.handleClick = this.handleClick.bind(this);

In this example the react component has a buttons, the click event of the button is bound to a handler function handleClick(). In the handler we change the state of the component.

setState example in React

The setState() method is used to change the state values of a React Component. After the component is initialized we can call setState to change specific state properties, setState() updates the components state and triggers Render() of the component. Based on the updates in state the component in re-rendered.

In this example we will initialize a component with a property show with default value false. We have a button Show/Hide the click event of the button toggles the value of the state using setState(), based on the current value of the state property the component will show/hide the message "Hello State".