Components and Props in REACT JS

Posted By : Shilpa Adlakha | 29-Jun-2017

Components and Props in REACT JS

Components allows you to divide the UI into independent, reusable parts.Components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.

Functional and Class Components:

Consider an example below:

function Myfunction(props) {
  return <h1>Hello, {props.name}</h1>;
}

The above defined function is a valid React component because it takes  only one value as a"props" object argument with data and gives  React element. These components  are known as "functional" because they are JavaScript functions.

Now, the same above code but written in different manner in react js:

class Myfunction extends React.Component {
  render() {
    return <h1>Welcome, {this.props.name}</h1>;
  }
}


Rendering a Component:

Elements can also represent user-defined components:

Forexample:

const data = <Myfunction name="Sachin" />;


In react,the element which represents user-defined component, it passes JSX attributes to this component as a single object. These object are named as "props".

For example, this code renders "Welcome, Sachin" on the page:


function Myfunction(props) {
  return <h3>Welcome, {props.name}</h3>;
}

const data = <Myfunction name="Sachin" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);


We call ReactDOM.render() with the <Myfunction name="Sachin" /> element.
React calls the Myfunction component with {name: 'Sachin'} as the props.
Our Myfunction component returns a <h3>Hello, Sachin</h3> element as the result.
React DOM  updates the Document object model to match <h3>Hello, Sachin</h3>.


Composing using other component:

Components can use other components in their output. This lets us use the same component abstraction for any level of detail.
The button,icon etc in React apps, all those are commonly expressed as components.

For example: we can create an App component that prints welcome a number of times:

function Myfunction(props) {
  return <h3>Hello, {props.name}</h3>;
}

function App() {
  return (
    <div>
      <Myfunction name="Sachin" />
      <Myfunction name="Ankit" />
      <Myfunction name="Akshay" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

 


Thanks!

About Author

Author Image
Shilpa Adlakha

Shilpa is a bright Wordpress Developer, she has good knowledge of HTML, CSS, PHP and Wordpress.

Request for Proposal

Name is required

Comment is required

Sending message..