What I try to acheive is NOT JUST render a component by onClick but also pass a dynamic function to the component.
Restrictions
In the project there is Dialog component from the FluentUI. This dialog has open property which is boolean and can be triggered by that. On one of the pages we lots of buttos which need to trigger the <Dialog/> this is why I can't just paste this sample code and change open state:
<Dialog
cancelButton={()=>{setOpen(false)}}
confirmButton={handleOnclick}
header="Action confirmation"
open={open}
/>
Requirements:
- Dialog should be dynamic
- Must only be rendered when we press on some buttons
- Must execute function which is passed to it with
confirmButton
Simplified code
Here is the link to the sandbox. Here how it looks:
import React from "react";
export default function App() {
const [visible, setVis] = React.useState(false)
const Component = ({id,execute}:{id:number,execute?:any}) =>{
//this part here should stayed untouched
return visible ? <button onClick={execute(id)}></button> : <></>
}
const handleClick = (id: number,execute: any)=>{
setVis(true)
return <Component id={id} execute={execute}/>
}
return (
<div className="App" >
<button onClick={()=>handleClick(1,(id:number)=>{console.log(id)})}>First</button>
<button onClick={()=>handleClick(2,(id:number)=>{console.log(id)})}>Second</button>
</div>
);
}
The code tries to replicate my situation but more simple way. I'm trying to render a component which has a button to execute some code passed to it.
Problem: Component never displays