Learn React - Advanced React Cheatsheet - Codecademy
Learn React - Advanced React Cheatsheet - Codecademy
Advanced React
React CSS Styles
React supports inline CSS styles for elements. Styles
are supplied as a style prop with a JavaScript // Passing the styles as an object
object. const color = {
color: 'blue',
background: 'sky'
};
<h1 style={color}>Hello</h1>
/
Presentational and Container Components
A common programming pattern in React is to have
presentational and container components. Container class CounterContainer extends
components contain business logic (methods) and React.Component {
handle state. Presentational components render that constructor(props) {
behavior and state to the user. super(props);
In the example code, CounterContainer is a this.state = { count: 0 };
container component and Counter is a this.increment
presentational component. = this.increment.bind(this);
}
increment() {
this.setState((oldState) => {
return { count: oldState.count
+ 1 };
});
}
render() {
return <Counter count=
{this.state.count} increment=
{this.increment} />;
}
}
/
Static Property
In React, prop types are set as a static property
( .propTypes ) on a component class or a function class Birth extends React.Component {
component. .propTypes is an object with
render() {
property names matching the expected props and return <h1>{this.props.age}</h1>
values matching the expected value of that prop type. }
The code snippet above demonstrates how }
.propTypes can be applied.
Birth.propTypes = {
age: PropTypes.number
}
.isRequired
To indicate that a prop is required by the component,
the property .isRequired can be chained to MyComponent.propTypes = {
prop types. Doing this will display a warning in the year: PropTypes.number.isRequired
console if the prop is not passed. The code snippet };
above demonstrates the use of .isRequired .
Type Checking
In React, the .propTypes property can be used
to perform type-checking on props. This gives import PropTypes from 'prop-types';
developers the ability to set rules on what
data/variable type each component prop should be
and to display warnings when a component receives
invalid type props.
In order to use .propTypes , you’ll rst need to
import the prop-types library.
Controlled Components
A controlled form element in React is built with a
change handler function and a value attribute. const controlledInput = (
<input value={this.state.value}
onChange={this.handleInputChange} />
);