React Components
May 9, 2020
There are 2 types of components you can use in a React project:
- class
- functional
Class components
-
Both
React
andComponent
need to be imported from thereact
package. -
Can access a local
state
where data only needed in this component can be stored and managed (see example below). -
Can use lifecycle hooks (I'll be making a future post on this).
-
Can access
props
withthis.props.<data>
. -
Class name is capitalized.
-
The body of the component's function is wrapped in
render()
with it containing areturn
statement wrapping a single element in parentheses to allow multi-line code. All of the elements are wrapped in one tag.
render() {
return (
<div></div>
)
}
In this ShoppingCart
class component, there is an internal state called checkingOut
that is set to true
when the checkout button is clicked.
this.state.checkingOut
accesses the state data.
There is an expected value totalPrice
passed to the component.
import React, {Component} from 'react';
class ShoppingCart extends Component {
state = {
checkingOut: false
}
handleCheckout = () => {
this.setState({checkingOut: true});
}
render() {
return (
<div>
<p>Total price: {this.props.totalPrice}</p>
<button onClick={this.handleCheckout}>checkout</button>
<p>Checking out? {this.state.checkingOut ? 'Yes' : 'No'}</p>
</div>
);
}
};
export default ShoppingCart;
Used in another component:
import ShoppingCart from './component/ShoppingCart';
//...
<ShoppingCart totalPrice="0"/>
Functional components
-
Only
React
needs to be imported from thereact
package. -
Essentially are JavaScript functions.
-
Cannot use local state or lifecycle hooks.
-
In order to pass data to the component (known as
props
) it needs to be declared as a parameter and is accessed withprops.<data>
. -
The body of the component's function is wrapped in a single
return
statement.
import React from 'react';
const modal = (props) => {
return (
<div>{props.error}</div>
);
};
export default modal;
Used in another component:
import Modal from './component/Modal';
//...
<Modal error="Problem!" />