React Components
Simple…Dry…Organized..
What is a React.Component?
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Check out the official React documentation on components (Links to an external site.)
Let’s bring it down a notch..components help us keep everything organized and predictable. Each component contains a snippet of code that describes what it should render to the DOM. Pretty much like a template.
Ex. class Book extends React.Component {
render() {
return (
<div>
Dear Reader: So and So... has the perfect imagination.
</div>
)
}
}
export default Book;
A Book class declared extends
React.Component which provides built in methods and attributes. The only method React.Component must define is a render().
When a render() is defined it should explicitly return a provided render(). Teling React “Hey! When you put it in the DOM, this is what it should become”. React will create the element and add to the DOM which results in HTML.
Ex. of HTML created by this added to the DOM:
<div>
Dear Reader: So and So... has the perfect imagination.
</div>
Explanation please…
React will take JS code, interprets the special HTML/JavaScript Syntax (JSX) within render()’s return() statement and spits out regular html that users will see in the browser.
App is the Top-Level Component
Being at the top is great!
App the parent component in most cases will wrap around the other child components and render them.
class App extends React.Component {
render() {
return (
<div>
<Book />
<Another_Component />
</div>
)
}
}
In App Component’s render() we see “Howdy App
component! When you render, I want you to also be responsible for making both the Book
and the Another_Component
component!"
Components must also return a JSX Element.
Import Child(ren) Components into your Parent Component.
If exporting default class…(allowing it to be imported by another file.)
like so: import Book from './Book';
If exporting a “named” component (not default ) add {} around the class you’re importing like so:a “named” component
import {Another_Component} from './Another_Component';
import Book from './Book';
import {Another_Component} from './Another_Component';class App extends React.Component {
render() {
return (
<div>
<Book />
<Another_Component />
</div>
)
}
}
React definitely makes things easier for us. The larger the structure, the more necessity there is for separate and distinct compartments, and separation of concerns.
Happy Coding!
-#CodingEsty