A beginner’s guide to optional chaining
Hello there,
So, you’re probably wondering what optional chaining is and why it is even important. Well, you don’t have to worry no more. I also had my share of confusion when I had my first contact with it in a codebase that I was trying to work on. Now I know the nitty-gritty of how to use it, and I’d love to share it with you.
Before we continue, I would like to inform you that this is my first technical writing (ever) So let me know your thoughts in the comment section below.
Okay. Enough talk, let’s dive in
let us start with the formalities.
What is optional chaining (?. )
Optional chaining ?.
lets you read the value of the property of an object that is within a chain without having you write a condition.
Okay, let me show what I mean. Imagine you have an object of customers
which has a property location
that also has a city
say you want to get the value of city
but you’re not sure that location exists. Without optional chaining, you might do this
let customerCity = customer && customer.location && customer.location.city
Oh no! that’s too long! right?
well, all you have to do with optional chaining is
let customerCity = location.currentLocation?.city
if the location
is undefined
, instead of throwing a reference error, the customerCity
becomes null
Not only is this cool, shorter, and simpler, but it makes you feel like a senior developer.
Now, it doesn’t work for just objects, you can use the optional chaining for arrays and functions also.
obj?.[2]
obj.func(“arg”)?.value
Maybe you know this already but it wouldn’t hurt to remind you that Optional chaining cannot be used on the left side of an assignment. meaning you cannot do this.
let customer.location?.city = “Lagos”;
Optional chaining is supported in the latest CRA (create-react-app) version, but to enable it in an older version of react we’d have to use a babel plugin.
yarn add customize-cra react-app-rewired @babel/plugin-proposal-optional-chaining -D
OR
npm install customize-cra react-app-rewired @babel/plugin-proposal-optional-chaining
then, to enable you to override configuration, create a config-overrides.js file in the root of your folder and add the following code
const { useBabelRc, override } = require(‘customize-cra’);
module.exports = override(useBabelRc());
you can enable the plugin in the .babelrc file
{
“plugins”: [“@babel/plugin-proposal-optional-chaining”]
}
Okay, one last thing, we would have to modify the package.json file in the script section a little so it can run our config file and babel plugin, replace the script with the one below:
“scripts”: {
“start”: “react-app-rewired start”,
“build”: “react-app-rewired build”,
“test”: “react-app-rewired test — env=jsdom”
},
Okay, that’s it, we have successfully enabled optional chaining in the previous version of React.
I hope this explains why your colleague used ?.
in their code. Let me know what you think in the comment section below.