TextField Material UI in dark mode

Viewed 459

I have a basic implementation of dark mode with material UI and React, the question is how to make TextField helper text, label, border changing according to dark and light mode toggled. TextField is:

<TextField helperText='Sample text' label="Title" variant="outlined" />

Updated: It's necessary TextField to have dark colored helperText, label, border in light mode, and light coloured in dark mode. There is basic implementation of dark, light mode:

import { createTheme, ThemeProvider } from '@material-ui/core/styles'
import Paper from '@material-ui/core/Paper'
import Switch from '@material-ui/core/Switch'

function App() {

  const [dark, setDark] = useState(false)

  const theme = createTheme({
      palette: {
          type: dark ? 'dark' : 'light',
      },
  })

  return (
    <Router>
      <ThemeProvider theme={theme}>
          <Paper>
            <Header></Header>
<Switch checked={dark} onChange={() => setDark(!dark)} />
            <main className='py-3'>
              <Container>
                <Routes>
                  <Route exact path="/" element={<HomeScreen />}></Route>
             ...
                </Routes>
              </Container>
            </main>
            <Footer></Footer>

          </Paper>
      </ThemeProvider>
    </Router>
  );

}

export default App;

Some of the elements correspond to light, dark mode toggling, TextField not.

2 Answers

You can do it like this, as answered here Theme dark turns textfield to white I added the helper text:

import React from "react";
import TextField from "@material-ui/core/TextField";
import { createMuiTheme } from "@material-ui/core/styles";
import { ThemeProvider } from "@material-ui/styles";
import CssBaseline from "@material-ui/core/CssBaseline";

const theme = createMuiTheme({
  palette: {
    type: "dark"
  }
});

export default function FilledTextFields() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <TextField 
        id="myfilled-name" 
        helperText='Sample text' 
        label="Name" 
        variant="filled"
       />
    </ThemeProvider>
  );
}

If what you ask for is to change the style of hintText and label, you should see the Customization section of Material-UI

On the other hand, if you want to change the hintText itself on theme mode change, you have to use a global state to keep track of your theme mode.

const App = () => {
    const [isDark, setIsDark] = useState(false)

    return (
        <TextField helperText={!isDark ? 'Sample text' : 'Some other text'} label="Title" variant="outlined" />
    )
}
Related