React Components and Props in a nutshell.
If you’ve found this article you are familiar with the basics of javascript. When I first started learning Web Development, I had this idea that everything was going to be written in HTML with a little Javascript if you wanted to do something fancy. I now know that that isn't true. Javascript through the DOM manipulation can handle Most of the HTML but undoubtedly we’d have to write hundreds of lines of code and that is where React comes in handy.
Using vanilla Javascript to create and manipulate html elements will have you writing document.createElement or document.querySelector more than you’d like . React makes use of handy little things called Components. React components allow the developer to write clean readable code. Components in a nutshell are seperate Javascript files that handle one functionality or feature for the webpage.
There are two types of components Class and Functional, Class components must have a render method that renders HTML. they ae also used to manage State, I like to think of state as a storage container for data for later use.they aslo are respinsible for server calls like fetch requests.Functional components are kind of the opposite, I’ts written in plain javascript they accept props as arguments. Functional components are also stateless which means the simply recieve and display data.
Components can also pass informtion to eachother for later use, this can be done by passing Props from a parent component to a child component. these are ways to pass information from child to parent as well but today we are only focusing on the parent to child route.
import React, {Component} from 'react'
import Hello from './Hello'export default class Home extends Component {state = {
name: John
}
render() {return(<Hello name={this.state.name}>)}}
In the example above we have our parent component first it imports the Hello component which allows the the Home component to render it.Next we are storing the name John under the name key. We then pass this prop to our Hello component in the return statement. Next lets take a look at the Hello component.
import React, {Component} from 'react'export default class Hello extends Component {render() {return({<h1> `Hello ${this.props.name}!`</h1>})}}
With our Hello component what we are doing is rendering an h1 element. We are also making use of the information that was passed down as a prop, using string interpolation to access the name stored in the prop. The final product is an h1 that reads Hello John!.
While the above examples are very simple components are extremely useful tools to use when creating single page applications, and the more you work with them Class or Functional (its your choice which component to use) you’ll really get a feel for what you can do with them in terms of real world application.