What is a Components in ReactJS

Rumman Ansari   2022-12-15   Developer   react js > What is an Components ?   382 Share
Creating Components

The simplest way to define a component is to write a JavaScript function:


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

This accepts a single "props" object argument and returns a React element.

You can also use an ES6 class to define a component.


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

The above two components are equivalent from React's point of view.

Composing Components
  • They are the Components that refer to other components in their output.
  • This lets us use the same component definition with different props value.

For example, we can create a component App that refers another component Welcome in output:


function Welcome(props) {
  return <h1>Hello {props.name}</h1>;
}
function App() {
  return (
    <div>
      <Welcome name="Harry" />
      <Welcome name="Jerry" />
      <Welcome name="Jini" />
    </div>
  );
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Components must return a single root element. This is why we added a 

 to contain all the  elements.

Larger Components

You can break larger components into smaller reusable ones in React. For example, consider this Comment component:


function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

It accepts author (an object), text (a string), and date (a date) as props, and describes a comment on a social media website.

This component can be tricky to change because of all the nesting, and is also hard to reuse individual parts of it. Lets see how this larger component can be split into smaller one.

Extracting Components

Let us extract the Avatar component from the previous example:


function Avatar(props) {
  return (
    <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}

The Avatar does not need to know that it is being rendered inside a Comment. This is why we have given its prop a more generic name: user rather than author.