Enabling optional chaining in a create-react-app

let nestedProp = obj.first && obj.first.second;
let nestedProp = (obj.first || {second:'Default value'}).second;
let nestedProp = obj.first?.second;
$ yarn create react-app optional-chaining-demo
$ cd optional-chaining-demo
$ yarn add customize-cra react-app-rewired -D
$ yarn add @babel/plugin-proposal-optional-chaining -D
// config-overrides.js
const { useBabelRc, override } = require('customize-cra');
module.exports = override(useBabelRc());
// .babelrc
{
"plugins": ["@babel/plugin-proposal-optional-chaining"]
}
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom"
},
const Demo = ({ nestedProp }) => (
<>{nestedProp.first?.second}</>
);
// Displays hello world
<Demo nestedProp={{ first: { second: 'hello world' } }} />
// Does not display anything
<Demo nestedProp={{ first: {} }} />
const Demo = ({ nestedProp }) => (
<>{nestedProp.first ? nestedProp.first.second : ''}</>
);
const Demo = ({ nestedProp }) => (
<>{nestedProp.first && nestedProp.first.second}</>
);

--

--

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store