The properties and functionalities of React components
A React component requires the
React-DOM dependencies, and then extends from the
constructor(props)function is needed for included properties and state values.
- Properties are values passed in when the component is called, such as label text.
- State are set internally in every component and change as the component is interacted with, such as if a menu is opened or not in the below example.
- Functions can also be defined inside the component and used in the render to trigger different interactions and effects. In the example below, the
toggleMenu()function is defined and set as a click event.
- The markup is only put for
return. Other code can be written before it in the function.
- The markup is only put for
- The file’s end should export the component so others can use it.
Once the component is defined and exported, it can be imported and rendered like so. This is also where other properties will be passed in.
Passing Functions to Components
There’ll likely be times where one component uses another, but the child component needs to trigger a change in the parent’s state. This requires:
- Creating a function that adjusts the state as needed in the parent
- Passing this function down to the child
- Linking the function to a click event in the child
For example, if we want to make a counter component with buttons that increase or decrease a count, we’d define these functions in the Counter and then pass them to the Button component.
Then in the Button, we reference this function by the property we passed it as for an
This way we can pass a function and needed parameters to the child component, while keeping the child component structured to accept other kinds of functions from other components that may need it. If the function your passing uses no parameters, you can just write the above like this:
Don’t include the parenthesis at the end of the function here, or else it will be called on page load. Here’s more info on passing functions to components.
Wrapping Children Components
Components can also be designed to yield to other HTML or components. For example, one component may create a wrapper around whatever else is passed in.
Wrapper component would need to do this so it renders what’s inside:
Lifecycle hooks are functions that a component will automatically look for and run when rendering or removing a component (referred to as mounting). For example, you can run code right before a component renders by using the
componentWillMount function, or while it’s being removed with the
A common use would be pulling in data from an API, and setting the state before the component renders.
This way data can be pulled from an external source, use promises to wait for the response, and include all the needed data in the render cycle.