Showing posts with label state. Show all posts
Showing posts with label state. Show all posts

Wednesday, August 8, 2018

props example in React

props or properties in React is a way in which we can pass data between components in a React page. Usually props are passed from the parent component to the child/nested components.  props are immutable they are passed from the parent/container component to the child components.

In this example we shall see on how to pass props in a parent component and pass it to the child/nested component.

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".

state example in React

State in a React Component is the components data store, all data required by the component are stored in the components state. State is nothing but a JavaScript object with properties to store each state value. The initial state of the component is set on the constructor of the component. using this.state = {}. After initializing the state can be changed using setState().

In this example we will have a time property in the state which will be displayed in the component. When the component initializes the time property is set to the current date/time and the time is displayed in the component.