Presentational and Container components
In this article we will learn about presentational and container components with example
Presentational Components
- Responsible only for rendering views. its all about how things will appear on the front end, for example (Markup, Style)
- Its main focus is on UI.
- These components weren't in direct communication with services or other data sources.
- Mostly, they get information via props and displays. they don't have a state of their own.
Container Components
- Responsible for handling dynamic tasks including data retrieval and state updating etc
- Deliver data to the presentational component via props
- Maintain state and communicate with data source
Code Example of Presentational Component
import React from 'react'
// receiving props in Presentational Component
export default function Presentational({ users }) {
return (
<div>
<h1>I am Presentational Component</h1>
{/* displaying props Data */}
<ul>
{users ? users.map((user, index) => {
return (<li key={index}>{user.name}</li>)
}) : "Loading . . ."}
</ul>
</div>
)
}
Code Example of Container Component
import React from 'react'
import Presentational from './Presentational'
export default function Container() {
const [data, setData] = React.useState();
// interacting with api to get data
React.useEffect(() => {
try {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(jsonData => setData(jsonData))
}
catch (e) {
console.log("Error : " + e)
}
}, [])
return (
<div>
{/* passing data to Presentational via Props */}
<Presentational users={data ? data : null} />
</div>
)
}
Thanks...
Nice work !!
ReplyDelete