Learning React Day 2
Second day in my learning log to understand and apply React into future personal and work-related Web projects.
Following up from my previous learning log entry I've started to build my first React component learning through React Fundamentals. One of the key ingredients of a React component are Props which form a parameter within functions to control what content is displayed such as an image path, a piece of text or numeric value.
We can use PropTypes within React to validate props and determine their type which might be a string, number, function or boolean value. PropTypes are no longer an inherent feature of the core React module so just like with any other module it now needs importing anywhere it's used.
import PropTypes from 'prop-types';
Understanding 'this' keyword
At this point we dip out from language specific to React and review the purpose of 'this' from a wider context.
Four types of binding exist and each have their uses in React:
- Implicit Binding 'this' is passed as an argument or for when a value is returned
- Explicit Binding Indicates what the context of 'this' will be using call, apply or bind
- new Binding 'this' is bound to the new object being constructed
- window Binding When 'this' is bound to the window object or undefined if in strict mode
Using the right binding method(s) will be of particular use for building React components to ensure the correct state is being set between different objects in the DOM such as active menu items and responding to interactions by the user in the case of dynamic forms. The more interacting components we have and the more content/data each contain/process: the more each of these binding methods are required to pass different arguments, change contexts and communicate to other functions inside and outside of component being built.
The example written up here follows on from a tutorial I worked through by Tyler McGinnis linked to in this post's references below. I went one further step to modify the way an active state is applied using a class name rather than inline styling.
Reference + reading
React Training React Fundamentals