Components

Class Components

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

Functional Components

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

React functional components are like JavaScript functions.

Rendering a Component

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 :

  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>.

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

Composing Components

  • Components can refer other components in their output.

  • Props are read only.

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.

function sum(a,b){        /* pure function */
    return a+b;
}
function withdraw(account, amount){        /* impure function */
    account.total -= amount;
}

All React components must act like pure functions with respect to their props.

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

Last updated