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 :
We call
ReactDOM.render()with the<Welcome name="World" />element.React calls the
Welcomecomponent with{name: 'World'}as the props.Our
Welcomecomponent returns a<h1>Hello, World</h1>element as the result.React DOM efficiently updates the DOM to match
<h1>Hello, World</h1>.
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;
}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
Was this helpful?