Reactjs : How to Pass values and arrays as props to React Component and access them

In this article, we will see how to pass data as props or properties to a component in React.js and how to access the data inside the component.

1. Pass data as props to React Component

Syntax to pass data to React Component is as follows :


ComponentName propertyName=“propertyValue”

Properties can be accessed in React Component as :


{this.props.propertyName}

 

Example : Passing data to Component in Reactjs

ReactDOM.render(<App name="John Doe"/>, document.getElementById('root'));

Example : Reading property passed in Reactjs

The name property can be accessed in the Component using this.props as shown below :

class App extends Component {
  constructor(props) {
     super(props);
  }
  render() {
    return (
      <div className="App">
        Hello {this.props.name}!!
      </div>
    );
  }
}

Output:

react properties
 

2. Passing different types of data (number, String, Date) as properties

For numeric and date values, we don’t need to pass them with double quotes, but we can specify them within curly braces as Javascript.

In the below example, String, number and Date values are passed to a react component Hello.

Example Passing String, number and Date to Reactjs Component

ReactDOM.render(<Hello name="John" age={30} date={Date()}/>, 
                document.getElementById('helloContainer')
);

class Hello extends Component {
    constructor(props) {
     super(props);
    }
  render() {
    return (
      <div className="helloContainer">
        <h4>Hello {this.props.name}, age {this.props.age}!!</h4>
        Current date is {this.props.date}
      </div>
    );
  }
}

Output:

react passing different props
 

3. Pass array as Props in React

For passing an array as props to a component, it should be in valid Javascript array syntax as shown below. We can access the array elements in the component in same way as other props and then use Javascript functions to manipulate the data.

Here is an example that passes an array of names to a React component Hello and the component joins the array elements by commas using the Javascript Array join() function.
 

Example Pass array as Props in React

ReactDOM.render(<Hello names={["Ajay","Bobby","Chitra"]}/>, 
                document.getElementById('helloContainer')
);

 
class Hello extends Component {
    constructor(props) {
        super(props);
      }
  render() {
    return (
      <div className="helloContainer">
        <h4>Hello {this.props.names.join(", ")}</h4>
      </div>
    );
  }
}

Output:

arrays as props in react
 

© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags