Blog>
Snippets

Fallback and Default Values with Inject

Explain how to define fallback values when injecting a property that might not be provided by an ancestor component.
import React, { useContext } from 'react';

// Create a context
const MyContext = React.createContext();

function MyComponent() {
  // Use useContext hook to inject the context into your component
  // If no value has been provided by a Provider,
  // useContext will return the default value defined in createContext (null in this case).
  const contextValue = useContext(MyContext) || 'default value';

  return (
    <div>
      {contextValue}
    </div>
  );
}

export default MyComponent;
This piece of code demonstrates how to use the useContext hook to inject a context in a child component. The fallback value is set as a string 'default value', which will be used if no Provider is found up in the tree for this context.
import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './MyComponent';

// Set up a Provider without a value
class App extends React.Component {
  render() {
    return (
      <MyContext.Provider>
        <MyComponent />
      </MyContext.Provider>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
In this part of the code, we simulate a scenario where a context Provider is used without passing an explicit value. The MyComponent will then use its default value as a fallback.
import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './MyComponent';

// Set up a Provider with a value
class App extends React.Component {
  render() {
    return (
      <MyContext.Provider value={'provided value'}>
        <MyComponent />
      </MyContext.Provider>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
Here is an example where the Provider is given an explicit value. The child component MyComponent will receive and use the 'provided value' instead of the default one.