React Fundamentals. Components

Programming has many similarities with real-life examples. For instance, when we think of a Prototype, we think of commonalities adding specific properties that make it unique, like all the cars have wheels, engines, etc., but have different make and models. When we think of React Components, we think of many reusable tools combined together that can help solve issues both separately and as a whole. The Components are the soul and the heart of the React library that represent reusable JavaScript functions which can be used and fixed separately, thus answering to the separation of concerns concept and making the overall code less error-prone. They are like separate stones that a huge cathedral is built from. As common functions in JavaScript can take arguments, likewise the Components in React can take props (properties).

Theindex.js file is the one core file in our application which connects all the React components (usually wrapped in a singleApp component) with HTML gateway, commonly reached by document.getElementById('root'). We only need to import Appcomponent, while all other components are, in their turn, imported in it.

ReactDOM.render(<App/>, document.getElementById('root'))

Different components are nested in the top-level App component (conventional name), and the latter has access to the outer world (virtual DOM) via ReactDOM.render(<App/>, document.getElementById('root')). ReactDOMrender() accepts 2 arguments, the first argument is the React element (like App component), and the second argument indicates wherein the visible world (<div id="root"></div>) this component should be rendered to. This second argument is the DOM container node in your HTML file. What will happen should we insert more that one element instead of single App?ReactDOM.render() will give us an error if we try to pass more than two arguments in total, but we can bypass this error by simply wrapping our multiple elements in div tags or React.Fragment(shorthand <></>), for instance, <div><Artist/><Song/></div>. In this case, we don’t violate this requirement as the components are wrapped in a single element, either<></> (or<React.Fragment/>) or div. In my opinion, React.Fragmentis a very convenient and elegant way of wrapping elements while, as they grow in number and complexity, you can easily end up with plenty of div -s, thus making your code messy.

We can build components or by declaring vanilla JavaScript functions or by writing ES6 class. Depending on the method we choose the syntax would be different.

If we convert it to class, it will look like this

Now we have a class component which extends React.Component, constructor which receives props, which are passed into super(props). You may notice that we added state and renderas well. Too much code? Actually, there is a shorter way of writing the exact same thing

This is much nicer and eliminates the necessity of repetition. The syntax has resemblance with plain HTML, but as we may predict, we are not allowed to write HTML in React. It looks like a combination of HTML + JavaSciprt and is called JSX (JavaScript extension), which compiled with Babel so that it looks like injected HTML. Meanwhile, JSX is able of doing much more, like performing programmatic operations, so don’t mess with simplistic markup language up!

Ok, so let’s build two components which are closely related to each other, where Artistis parent and Songis child

class Artist extends React.Component {
state = { name: "Bono", age: 60 };

render() {
return (
<>
<Song name={this.state.name} age={this.state.age} />
</>
);
}
}
export default Artist;

Artistis the parent component. It has state which is filled with dynamic data. It’s an object with key/value pairs. Note the second line of the code where we import Song. Remember here three things. First, you import the child component (import Song from './Song'). Second, you pass down this child component as a returned value of the parent component (<Song/>). Third, you can choose which state of the parent component to pass as props to the child (<Song name={this.state.name} age={this.state.age}/>). This props can now be invoked from the child component via this.props.name (so this.state.name of the Artist parent becomes this.props.nameof the Songchild!!).

export default class Song extends React.Component {
state = {title: "Every Breaking Wave"}

render() {
return (
<>
<h2>{this.props.name} is {this.props.age} years old. My favorite song is {this.state.title}.
</h2>
</>
);
}
}
// Bono is 60 years old. My favorite song is Every Breaking Wave.

Note that in the first case the syntax is class Artist extends React.Componentand, at the bottom, export default Artistbut in the second example, we wrote everything in a single line, export default class Song extends React.Component. Which way to choose is completely up to you as long as you don’t forget to import and export your components.

So what magic happens here as a child component’s return value? Nothing magical here actually, we just say React in its language to return the name (name) value of the parent component’s (Artist)stateof this Songcomponent (this). The same is true for this.props.age. The same isn’t true for the this.state.title. Why? That’s a good question the answer of which you can find below as we are to clearly distinguish statefrom props.

The differences between props and state

These two parameters are initially easy to mix and get confused about. There few things that can help you distinguish the differences once and for all. The first distinction is that stateis dynamic whereas props are static. For instance, when we increase a counter value or fill in a form, it changes at our every interaction (click or change, or, if converted to React terminology, onClick or onChange). As a contrast, the props are immutable. The second difference is that state is intrinsic to the Component it’s used in when props are inherited from a parent Component. In its turn, the parent component passes down props to its children. When, in the child component, we type this.props.name, that means that we want to get thename value of its parent. Thirdly, the state is private and controlled whereaspropsare uncontrolled.

The last thing that we need to do in order for our components to be visible, is to insert them into the top-top level Appcomponent.

export default function App() {
return (
<div className="App">
<Artist/>
</div>
);
}

In the same manner, as we imported Songas a child of Artist, the Artist becomes a child of the App(So the Appis the grandparent of Song).

Conclusion

React components make your code more flexible, enable to separate and solve issues isolatedly, improve isolatedly, thus making the code less erroneous, pass down, and receive props between components. These qualities become more and more important as your applications grow in volume and complexity and are essential in larger-scale applications. With this great library, you’ll be able to overcome modern programming challenges.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store