State is similar to props, but it's private and fully controlled by the component.
You can convert a function component to a class in five steps:
- Create an ES6 class, with the same name, that extends React.Component.
- Add a single empty method to it called render().
- Move the body of the function into the render() method.
- Replace props with this.props in the render() body.
- Delete the remaining empty function declaration.
A React component's lifecycle contains phases for creation and deletion. These are called mounting and unmounting. These can be thought of as "setup" and "cleanup".
We can declare special methods on the component class to run some code when a component mounts and unmounts. These methods are called "lifecycle methods."
Three things you should know about setState()
- Don't modift state directly
- State Updates May Be Asynchronous
- State Updates are Merged
Handling events in React is similar to handling events on the DOM, although there are some syntax differences:
- React events are named using camelCase
- With JSX you pass a function as the event handler, rather than a string.
You also cannot return false to prevent default behavior in React- you must call preventDefault explicitly.
When using React, you generally don’t need to call addEventListener to add listeners to a DOM element after it is created. Instead- provide a listener when the element is initially rendered.
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
The above two lines are equivalent, and use arrow functions and Function.prototype.bind respectively.
In both cases, the e argument representing the React event will be passed as a second argument after the ID. With an arrow function, we have to pass it explicitly, but with bind any further arguments are automatically forwarded.
You can render React components that hold the behavior you need distinctively- meaning you can render only some, depending on the state of the application. Conditional rendering works much the same way as in JavaScript- using operators like if or the conditional operator to create elements representing the current state.
You can use variables to store elements, which will help conditionally render a part of the component without changing the rest of the output.
You can embed expressions in JSX by wrapping them in {}. Including JavaScript logical && Operator- useful for conditionally including an element.
Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition ? true : false.
It is up to you to choose an appropriate style based on what you and your team consider more readable. Keep in mind, whenever conditions become too complex, it might be a good time to extract a component.
If you ever wanted a component to hide itself even though it was rendered by another component. Return null, instead of its render output.