Skip to content
This repository was archived by the owner on Jan 13, 2025. It is now read-only.
This repository was archived by the owner on Jan 13, 2025. It is now read-only.

An example of integrating with React without the Foundation / Adapter pattern #407

@davidharting

Description

@davidharting

Notes

This is not a feature request or a bug, so if there is a better way to communicate this, please let me know and I will close this PR.

My main purpose in opening up this issue is to get feedback on this approach for integrating material-components-web with React. Does this simple approach miss anything important?

Integration approach

I am attempting to use material-components-web with React for a production web app. I found a way of integrating with React that is much more lightweight than the Foundation / Adapter pattern.

The basic idea is create and destroy vanilla material-component-web JS components based on the React lifecycle. I hook up the material component to the right element of the DOM by using the react API to get a refence to a DOM element.

Example

import React from 'react'
import { textfield } from 'material-components-web'

export default class TextField extends React.PureComponent {
  
  // Instantiate the vanilla material component once the react component mounts
  componentDidMount() {
    this.mdcComponent = new textfield.MDCTextfield(this.mdcMount)
  }

  // Clean up the vanilla material component along with the react component 
  componentWillUnmount() {
    this.mcdComponent.destroy()
  }

  render() {
    // Note in the second opening div how I get a reference to the DOM element of the text field
    return (
      <div className="mdc-form-field">
        <div className="mdc-textfield" ref={(div) => { this.mdcMount = div }}>
          <input
            type="text"
            className="mdc-textfield__input"
            id="demo-input"
            onChange={this.props.onChange}
          />
          <label htmlFor="demo-input" className="mdc-textfield__label">
            {this.props.label}
          </label>
        </div>
      </div>
    )
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions