React.js: TextField code sample using MaterialUI

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

I was developed with React.js, and I had trouble to using Material UI components, so I wrote down a note of the code.
Since React.js and Material UI are still developing, their manners change slightly, so it is quite difficult.
I hope you find it useful for those who are in trouble.

Sample pattern that does not work TextField

Below is a sample pattern that does not work TextField using MaterialUI.
It seems that you need to import Material UI theme files and define initial values.

// sample001.jsx
// sample pattern that does not work
import React from 'react';
import TextField from 'material-ui/TextField';

export class Sample extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            value: 'Sample Value',
        };
    }


    render() {
        return (
          <div>
               <TextField hintText="Message Field"
	        floatingLabelText="MultiLine and FloatingLabel"
	        multiLine={true}
	        rows={2} />
          </div>
        );
    }
}

Sample pattern that does work TextField

Below is a sample pattern that does work TextField using MaterialUI.
Define the initial value of the theme file like const styles, const muiTheme.
DeepOrange500 is a color theme set that I chose appropriately, and you can choose from many others.

// sample002.jsx
// Sample pattern that does work
import React from 'react';
import {deepOrange500} from 'material-ui/styles/colors';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import TextField from 'material-ui/TextField';


const styles = {
    container: {
        textAlign: 'center',
        paddingTop: 200,
    },
};

const muiTheme = getMuiTheme({
    palette: {
        accent1Color: deepOrange500,
    },
});


export class Sample extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            value: 'Sample Value',
        };
    }


    render() {
        return (
          <MuiThemeProvider muiTheme={muiTheme}>
            <div>
                 <TextField hintText="Message Field"
                  floatingLabelText="MultiLine and FloatingLabel"
                  multiLine={true}
                  rows={2} />
            </div>
          </MuiThemeProvider>
        );
    }
}
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.