'How to give Typography-like style to an input element with Material-ui?
I would like my Typography field to become editable, so I transform it into an input.
Now I would like this input to have the same style.
How to do it?
I tried copying the produced css to the input, but it is tedious and seemed not perfect.
Here is a code sandbox to illustrate: https://codesandbox.io/s/flamboyant-stonebraker-le1eq?file=/index.js
Solution 1:[1]
I found a workaround for you, but keep in mind that this is not ideal because if you change the current Typography component you have to find its classes again in the chrome devtools, and also the typography with the diaplay: none
is necessary for material to render the styles...
import React from "react";
import ReactDOM from "react-dom";
import { Button, InputBase, TextField, Typography } from "@material-ui/core";
function App() {
const [isEditing, setIsEditing] = React.useState(false);
const [value, setValue] = React.useState("Edit me");
const toggleIsEditing = () => setIsEditing((b) => !b);
if (isEditing) {
return (
<div style={{ display: "flex", alignItems: "center" }}>
<input
className="MuiTypography-root MuiTypography-h4 MuiTypography-displayInline"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Typography style={{ display: "none" }} />
<Button size="small" onClick={toggleIsEditing}>
Done
</Button>
</div>
);
}
return (
<div style={{ display: "flex", alignItems: "center" }}>
<Typography variant="h4" display="inline">
{value}
</Typography>
<Button size="small" onClick={toggleIsEditing}>
Edit
</Button>
</div>
);
}
ReactDOM.render(<App />, document.querySelector("#app"));
Solution 2:[2]
<Typography suppressContentEditableWarning={true} contentEditable={true} className={text} onChange={handleChange}>
Some text
</Typography>
Css (to prevent the nasty looking border, when you click into the Typography):
text: {
outline: `0 solid transparent`,
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MrHaze |
Solution 2 | alisacodes |