What is a Components in ReactJS
Creating Components
The simplest way to define a component is to write a JavaScript function:
function Welcome(props) { return Hello, {props.name}
; }
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 Hello, {this.props.name}
; } }
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 Hello {props.name}
; } function App() { return (); } ReactDOM.render(, document.getElementById('root') );
Components must return a single root element. This is why we added a You can break larger components into smaller reusable ones in React. For example, consider this Comment component: It accepts 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. Let us extract the Avatar component from the previous example: 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.
elements.
Larger Components
author
(an object), text
(a string), and date
(a date) as props, and describes a comment on a social media website.Extracting Components