In React, Components are the basic build blocks, one of the core concepts. We build user interfaces (UI) through components.
React lets us combine the markup, CSS, and JavaScript into custom “components,” reusable UI elements for your app. Similar to HTML tags, you can use components like the following to design the pages.
<Layout>
<Header>
<Navigation />
<Search />
</Header>
<Content>
<BannerImage />
<PageContent />
</Content>
</Layout>
A React component is a JavaScript function that serves the markup. Following is an example of a sample component.
export default function Header() {
return (
<header className="bg-white shadow-sm">
<div className="mx-auto max-w-7xl py-4 px-4 sm:px-6 lg:px-8">
<h2 id="headingText" className="text-lg font-semibold leading-6 text-gray-900">Header text</h2>
</div>
</header>
)
}
The export default
is a standard JavaScript syntax. This lets us mark the primary function in a file as exportable, and we can import that function into other files.
JSX is a syntax extension for JavaScript called JavaScritp Extension. JSX allows us to write HTML-like markup inside a JavaScript file. In the React component, we can have logic and markup together, as shown following.
export default function SampleButton() {
function handleClick() {
alert('I am clicked!');
}
return (
<button id="sample_button" onClick={handleClick}>Click me</button>
)
}
There are a few rules of JSX which are mentioned as follows:
Return a single root element – To return multiple elements from a component, wrap all the elements with a single parent tag.
<div>
<h1>This is header</h1>
<p>This is paragraph</p>
<img src="" alt="This is image" />
</div>
If we do not want an extra <div>
, then we can use <>
and </>
instead:
<>
<h1>This is header</h1>
<p>This is paragraph</p>
<img src="" alt="This is image" />
</>
Close all the tags – JSX requires tags to be explicitly closed: self-closing tabs like <link> must become <link>
and wrapping tags like <div>test
must be written as <div>test</div>
camelCase most things – JSX compiled into JavaScript, and the attributes written in JSX become keys of JavaScript objects. So, in React, many HTML and SVG attributes are written in camelCase. For example, instead of background-image
you use backgroundImage
. The keyword class
is reserved, and hence in React you write className
instead of applying the CSS class to an element.