Sometimes, you have several React components that use the same initial state. You can implement a base component that sets this initial state. Then, any components that want to use this as their initial state can extend this component. Let's implement a base component that sets some basic state:
import { Component } from 'react';
import { fromJS } from 'immutable';
export default class BaseComponent extends Component {
state = {
data: fromJS({
name: 'Mark',
enabled: false,
placeholder: ''
})
};
// Getter for "Immutable.js" state data...
get data() {
return this.state.data;
}
// Setter for "Immutable.js" state data...
set data(data) {
this.setState({ data });
}
// The base component doesn't actually render anything,
// but it still needs a render method.
render() {
return null;
}
}
The state is an immutable Map. This base component also implements immutable data setter and getter methods. Let's implement a component that extends this one:
import React from 'react';
import BaseComponent from './BaseComponent';
// Extends "BaseComponent" to inherit the
// initial component state.
export default class MyComponent extends BaseComponent {
// This is our chance to build on the initial state.
// We change the "placeholder" text and mark it as
// "enabled".
componentDidMount() {
this.data = this.data.merge({
placeholder: 'Enter a name...',
enabled: true
});
}
// Used to set the name state whenever the input
// value changes.
onChange = ({ target: { value } }) => {
this.data = this.data.set('name', value);
};
// Renders a simple input element, that uses the
// state of this component as properties.
render() {
const { enabled, name, placeholder } = this.data.toJS();
return (
<label htmlFor="my-input">
Name:
<input
type="text"
id="my-input"
disabled={!enabled}
placeholder={placeholder}
value={name}
onChange={this.onChange}
/>
</label>
);
}
}
This component doesn't actually have to set any initial state because it's already set by BaseComponent. Since the state is already an immutable Map, you can tweak the initial state in componentDidMount() using merge(). Here's what the rendered output looks like:

If you delete the default text in the input element, you can see that the placeholder text added by MyComponent to the initial state is applied as expected:

You can also change the text to something else and the onChange() event handler will set the name state accordingly.