Can you guys give me an idea how to pass data to a modal according to a specific user? I have an array containing user data. When I click on the corresponding user, I need to open a modal with his data like name and email. How would I do that?
CodePudding user response:
Basically, you would solve this through React's props, as follows:
export interface UserData {
name: string
email: string
}
export interface ModalProps {
user: UserData
}
export const Modal: React.FC<ModalProps> = ({ user }) => {
// TODO: render modal here
return <></>
}
It would be rendered as follows:
const App: React.FC = () => {
return <Modal user={{ name: 'John', email: '[email protected]' }} />
}
If your user changes, you have to define a state in the respective component and call its setter function to render the component again:
const App: React.FC = () => {
const [user, setUser] = React.useState<UserData>({
name: 'John Doe',
email: '[email protected]'
})
// if needed, call setUser(newUser) to update the modal
return <Modal user={user} />
}
You'd better get to know the React basics. The React docs are a good foundation:
- Hello World
- Introducing Hooks
- Using the State Hook
- Rules of Hooks
- and so on...