ReactJS Components and Props

Hi, I am your friendly developer Nikhil. I have been working on my way to get around the complexities of ReactJS(The JavaScript Library). In this document, we will talk about how props and components work.

Components

A hefty and modular term in ReactJS which makes us nervous but don't worry, cause it is not as terrifying as it looks... Coming from JavaScript background we know functions right.. so in ReactJS those javascript functions which are put in separate file to be passed back to the root div element as react is known as Component.

e.g.

From Person.js
import React from 'react'

const person =()=> {
return(<div><p>I am a Component</p></div>);
export default person
From App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person/Person'

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <h1>Hi this is Nikhil</h1>
        <Person/>
      </div>
  }
}

export default App;

Props

So, above we have seen components, which are basically functions, we can write JSX code in these functions for rendering as react element, but the main purpose we use function in any language including react is to make our site dynamic, say instead of hardcoding my introduction entirely, I decide to make my Name, Age and Hobbies to be passed as object to the component person which we made above. It is very easy and can be done like this.

e.g:

App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person/Person'

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <h1>Hi this is Nikhil</h1>
        <Person name="Nikhil" age="24">Hobbies : Travelling</Person>
      </div>
    );
  }
}

export default App;
Person.js
import React from 'react';

const person = (props) =>{
    return (
    <div>
        <p>I'm {props.name} a {props.age} Year old trying to learn ReactJS</p>
        <p>{props.children}</p>
    </div>
    )
};

export default person

so, as we saw in above code in Person.js file, the props refers to properties which contain the data object and is passed to the component from App.js file. This object is accessible using the key name & age as mentioned in Person.js file.

you may have seen, something like props.children in the Person.js file, it is used to render the object which has been passed as simple JSX in the root element like Hobbies : Travelling.

Stay Tuned for new blogs about my experiments with ReactJS.