Components in React. What are they?
--
Components are the backbone of your code in React. They help isolate snippets of code to be able to use them more efficiently throughout your application. Components allow us to simplify how we render our code, as well. By reading along, you may notice a lot of syntax comparable to HTML. So let’s get started.
First, it’s important to distinguish between static components and dynamic components. Static components are just snippets of code that aren’t going to change or have any values passed into them. Dynamic components are the opposite of that, where we have our code rendering values that have been passed into the component. For example, let’s think about how Twitter might work. A static component of Twitter may be the logo at the top of the webpage that redirects you to the homepage when you click it. A dynamic component would be a tweet rendering whatever content a user has typed into and submitted.
This is staticclass Logo extends React.Component { // basic component syntax
render() {
return ( // necessary to actually output the data
<img src="twitterlogo.png"/>
)
}
}
This is dynamicclass PostText extends React.Component { // basic component syntax
render() {
return ( // necessary to actually output the data
<div>
{this.props.textContent} // dynamically insert values
</div>
)
}
}
Using this is key to how dynamically inserting values into components works. MDN has a really good page about how this works. By accessing the attributes (or properties) in an object, we can insert them into the components and render them accordingly.
<Post user='Cher' text='something something life after love'class Post extends React.Component {
render() {
return (
<div>
<h1>{this.props.user}</h1> <h4>{this.props.text}</h4>
</div>
)
}
}
This would now render depending on where you put it in your code.
There’s pretty much two types of components you can do. Class components, as I’ve used above, can use props and manipulate them however you wish. Class components are what you would want to use when working with state, as well. Class components also make use of the render() function as well.
Function components are very basic in how they work. They aren’t as adaptable as class components and don’t work with state. They also don’t use a render() function. Function components are typically for taking in props and creating JSX.
function Greeting(user){
return <div>Hello {user.name}</div>
}
Pretty much the same syntax, too.
Class components are usually what you want to work with since they can do everything function components can do and so much more. And yeah, that’s a basic overview of components!