in React, React Native

props and state in react

Props


When developing resuable component in react it is often necessary to pass static values and method between the component. In this case, props (properties)  plays a grate role.  So props can be term as attributes to component. Props are accessed by  {this.props} 

Default Prop Values


React lets you define default values for your props in a very declarative way:

var ComponentWithDefaultProps = React.createClass({
  getDefaultProps: function() {
    return {
      value: ‘default value’
    };
}
});

—————— or the other way  ———————-

class ComponentWithDefaultProps extends Component {
render(){
return(
 <h1>{this.props.val}</h1>
          );
}
}

ComponentWithDefaultProps. defaultProps = {
value:’default value’,
}

PropsTypes


The propTypes object allows you to validate props being passed to your components. 

import React, { Component,PropTypes } from ‘react’;

ComponentWithDefaultProps.propsTypes = {
functionName: React.PropTypes.func.isRequired,
txt: React.PropsTypes.string,
}

<ComponentWithDefaultProps style={styles.instructions}
functionName= {this.functionName.bind()}
txt=’sample text’
/>

here what isRequired saying is that ComponentWithDefaultProps must pass functionName props other wise  error will be generated for you  where as  txt props  is optional.

If we need to pass all the props of the parent to child then we can use following ways.

<ChildComponent {…this.props}/>

state


Each react component has its own state. State is a collection of values that need to be maintained by component itself.  State variable  are editable object parameters, which can be read and write  only by the component itself. Upon change in state value  it will get reflected as UI update. Here’s how we can initiate component state properties.

var MyComponent = React.createClass({
    getInitialState: function(){
        return {
           val: 5
        }
    },
    render: function(){
        return (
            <h1>{this.state.val}</h1>
        )
    }
});

 

—————— or the other way  ———————-

class MyComponent extends Component {

constructor(props) {
super(props);
this.incrementCount = this.incrementCount.bind(this);
this.state = {
val: 0,
}
}

render(){
return(
 <h1>{this.state.val}</h1>
          );
}
}

Now below is a  a very simple react native application with the use of state and props that will display click count.

14eq1a.gif

Download full source code of PropsAndState from github repo .
Make sure you run npm install inside PropsAndState directory.

Write a Comment

Comment

Webmentions

  • React Native – React Native

    […] props and state in react […]