# Components

#### Class Components

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

#### Functional Components

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

> React functional components are like JavaScript functions.

## Rendering a Component

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

const element = <Welcome name="World"/>;    /* User-defined component */

ReactDOM.render(
    element,
    document.getElementById('root')
);
```

What's happening here is :&#x20;

1. We call `ReactDOM.render()` with the `<Welcome name="World" />` element.
2. React calls the `Welcome` component with `{name: 'World'}` as the props.
3. Our `Welcome` component returns a `<h1>Hello, World</h1>` element as the result.
4. React DOM efficiently updates the DOM to match `<h1>Hello, World</h1>`.

{% hint style="info" %}
Component name should always start with Capital letter otherwise react treat them as DOM tags\
Example:\
`<div>` represents HTML div tag\
`<Welcome>` represents a react component
{% endhint %}

## Composing Components

* Components can refer other components in their output.
* Props are read only.

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

function App(){
    return (
        <div>
            <Welcome name="Sun"/>
            <Welcome name="Mars"/>
            <Welcome name="Earth"/>
        </div>
    );
}

const element = <App/>
ReactDOM.render(
    element,
    document.getElementById('root')
);
```

* A function or class which never modify its own props are called "pure" because they don't change their input and produce same result every time with the same inputs.

```jsx
function sum(a,b){        /* pure function */
    return a+b;
}
```

```jsx
function withdraw(account, amount){        /* impure function */
    account.total -= amount;
}
```

{% hint style="info" %}
**All React components must act like pure functions with respect to their props.**
{% endhint %}

> **props** get passed to the component (similar to function parameters) whereas **state** is managed within the component (similar to variables declared within a function).
