I started learning React yesterday and hence I thought I'll write articles about what I learned each day.
What are components in React?
Short answer: Components are independent and reusable block of code and return html using render() function.
Suppose we have the following UI:
So we will have components for each like Navbar component, sidebar component, component for article and footer.
React allows us to write components in two ways:
- Functional components
- Class Components
Writing your first React component
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Functional Components in React</title>
</head>
<body>
<div id="root"></div>
// Babel (To render JSX), React and ReactDOM
<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script type="text/babel">
function SayHello(){
return (<h1>Hello, World!</h1>);
};
ReactDOM.render(
<SayHello />,
document.getElementById('root')
);
</script>
</body>
</html>
Understanding above code:
We have a simple html document with div with id as root and some script files:
- Babel (used to render jsx)
- React and ReactDOM
In our inline script, we wrote our first functional component.
Function SayHello() returns jsx and thus we used imported babel.
Now, we render this JSX into out html with the help of render() function from ReactDOM.
render() accepts two arguments: render(WHAT TO RENDER, WHERE TO RENDER)
.
Hence our functional component SayHello() renders Hello, World!
into the div with id as root
.
Points to remember:
- Start component name with CAPITAL letter. (Capital CamelCase is preferred)
- Your component cannot return multiple elements. Therefore make sure to bind all of them into a single parent element. e.g.
<div>
<h1></h1>
<p></p>
</div>
Okay, that's all today. Hope you liked the article and would also like to hear from you to improve my ways of writing these articles.
Don't forget: I'm Noob writer after all 😁
Some Links to learn React:
Top comments (0)