# React & Material UI 備忘錄
## Material UI 使用
[Material UI 官網](https://mui.com/)
提供直接使用的 component ,Typography可由 [api](https://mui.com/api/typography/) 頁面查詢可以控制哪些變量,利如 <font color="#f00">variant</font>、<font color="#f00">color</font>...等
```react.js=
import React from "react";
import Typography from "@mui/material/Typography";
export default function Create() {
return (
<div>
<Typography variant="h2" color="secondary">Create a new Note</Typography>
</div>
);
}
```

## 基本 component 使用
* Container
* Button
* Icon
* Typography
* TextField
* RadioButton
## 修改預設主題項目
```react.js=
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { green, orange } from "@mui/material/colors";
const outerTheme = createTheme({
palette: {
primary: {
main: orange[500],
},
secondary: {
main: green[500],
},
}
});
```
## 修改部分styles
無法直接使用className來進行套用時
TextField is just a wrapper component of the Input inside it, to target the input for styling, you can use <font color="#f00">InputProps</font>:
``` react.js=
import { makeStyles } from '@mui/styles';
const useStyles = makeStyles({
field: {
marginTop: 20,
marginBottom: 20,
display: "block",
},
});
<TextField
InputProps={{
className: classes.field
}} />
```
## 更換頁面內容 re-render 需使用(useState hook)
```react.js=
import { useState } from "react";
const Home = () => {
//name為預設值'mario', setName為修改後的值
const [name, setName] = useState('mario');
const handleClick = () => {
// name = 'luigi';
setName('luigi');
}
return (
<div className="home">
<h2>Homepage</h2>
<p>{ name }</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
export default Home;
```
## useEffect 的使用
Tell React that your component needs to do something after render.
當第一次 render 後去 8000 port 取得notes頁面資料,由 setNotes 更新 notes 參數
```react.js=
export default function Notes() {
const [notes, setNotes] = useState([]);
useEffect(() => {
//使用fetch 呼叫restful api
fetch("http://localhost:8000/notes")
.then((res) => res.json())
.then((data) => setNotes(data));
}, []);
```
## 當form 表單submit,避免瀏覽器預設開啟新頁
```react.js=
//將event 傳入匿名函數 呼叫 e.preventDefault()
const handleSubmit = (e) => {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
```
# Reference
* https://github.com/iamshaunjp/material-ui-tut
* https://stackoverflow.com/questions/69557763/margin-not-working-in-textfield-using-mui-makestyles
* https://zh-hant.reactjs.org/docs/handling-events.html
* https://www.gushiciku.cn/pl/gaYM/zh-tw