I am developing a React.js application based on Material UI for a school project. My project is based on the React + Material UI + Firebase example found in the Material UI docs. Currently, I am trying to employ React Hooks
so I can avoid using Redux (and get better at something that'll be developing in the future). In the app component, they have an openDialog function, which operates as a way to open a modal based on the dialogId.
class App extends Component {
constructor(props) {
super(props);
this.state = {
signUpDialog: {
open: false
},
signInDialog: {
open: false
},
settingsDialog: {
open: false
},
signOutDialog: {
open: false
}
};
}
// CURRENT, NON-HOOKS WAY
openDialog = (dialogId, callback) => {
const dialog = this.state[dialogId];
if (!dialog || dialog.open === undefined || null) {
return;
}
dialog.open = true;
this.setState({ dialog }, callback);
};
They then have a Navbar than call this function with the corresponding dialog (eg onSignUpClick={() => this.openDialog('signUpDialog')}
) I am currently trying to move this over using hooks
Can someone please teach/help me convert this modular function for me!
const [dialog, setDialog] = useState({
isOpensignUp: false,
isOpenSignIn: false,
isOpenSignOut: false,
isOpenSetting: false
});
const handleDialog = e => {
setDialog({...dialog,[e.target.name]:true});
}
<button name= "isOpensignUp" onClick={handleDialog} />
<Dialog open={dialog.isOpensignUp}>
import React from 'react'
function App({ callback }) {
// if we just mind about the active dialog,
// we don't need to save the state of the others
const [dialog, setDialog] = React.useState(null)
// here useEffect is called every time, dialog changed,
// we also need to put `callback` in the array otherwise
// React throw a warning.
// React.useEffect act like `ComponentDidMount`, so we better
// check dialog is not empty otherwise it will call our callback
// straight away AFTER the render and that's not what we want
React.useEffect(() => {
if (dialog) callback()
}, [dialog, callback])
// You said we were in a navBar so i can assume you can do
// something like this
return (
<div>
{['signUp', 'signInDialog', 'settingsDialog', 'signOutDialog'].map(
elem => (
<div key={elem} onClick={() => setDialog({ [elem]: true })}>
{elem}
</div>
),
)}
</div>
)
}
export default App
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.