Importing and using vanila JS functions in React component - javascript

I am very new to react.js and JavaScript, so apologies in advance. I'm trying to integrate https://diagrams.net into other webpage using the file that's directly given by diagrams.net here:
https://github.com/jgraph/drawio-integration/blob/master/diagram-editor.js?fbclid=IwAR1FMViVLW3Tba8RqMOUJtv16vIvPPycLYyu4rEtRTbuhbyztlrLXu5UyHo.
So as it can be seen in this example here: http://jgraph.github.io/drawio-integration/javascript.html, when the user double clicks on the diagram, they should be redirected to diagrams.net web and draw their own diagram.
The problem is that my web is currently built on React, and all the diagrams.net is built on vanilla JS. By inspecting the example above, they apparently use:
<img
style="cursor:pointer;"
title="Click to edit image"
onclick="DiagramEditor.editElement(this);"
src="data:image/png;base64,iVBORw0...
in the HTML to display the image of the diagram. I've tried to change it to react-like by changing it to:
<img alt="Click to edit image"
onClick={EditDiagram.DiagramEditor.editElement(this)}
src="data:image/png;base64,iVBORw0..."/>
and importing the JavaScript file by import * as EditDiagram from "../components/workarea/workarea-diagram-editor";, but it is returning TypeError: Cannot read properties of undefined (reading 'editElement').
I've also tried using dangerouslySetInnerHTML like this:
<div
dangerouslySetInnerHTML={{
__html:
"<img style='cursor:pointer;'
title='Click to edit image' onclick='DiagramEditor.editElement(this);'
src='data:image/png;base64,iVBORw0...'/>",
}}/>
but this way, that DiagramEditor.editElement(this) cannot be accessed that way.
I've been trying to get this to work for past 12 hours, but just can't get it to work. Is there any way to make this work?
Thank you so much.
Below is the React code that the JavaScript is being added on.
const WorkArea = () => {
const router = useRouter();
const formik = useFormik({
initialValues: {
scenario: "This is scenario",
},
validationSchema: Yup.object({
scenario: Yup.string().max(255).required("Scenario is required"),
}),
onSubmit: () => {
router.push("/");
},
});
const [countList, setCountList] = useState([0]);
// const [inputList, setInputList] = useState([]);
const AddScenario = () => {
let countArr = [...countList];
let counter = countArr.slice(-1)[0];
counter++;
countArr.push(counter);
setCountList(countArr);
};
const DeleteScenario = () => {
let countArr = [...countList];
let counter = countArr.slice(-1)[0];
counter--;
countArr.pop(counter);
setCountList(countArr);
};
// const onAddBtnClick = (event) => {
// setInputList(inputList.concat(<SetScenario key={inputList.length} />));
// };
return (
<>
<Head>
<title>Work Area | Cybersecurity Requirements Generator</title>
</Head>
<Box
component="main"
sx={{
alignItems: "center",
display: "flex",
flexGrow: 1,
minHeight: "100%",
}}
>
<Container maxWidth="xl">
<NextLink href="/projects" passHref>
<Button component="a" startIcon={<ArrowBackIcon fontSize="small" />}>
Back to Projects
</Button>
</NextLink>
<form onSubmit={formik.handleSubmit}>
<Box sx={{ my: 3 }}>
<Typography color="textPrimary" variant="h4">
Use Case Diagram
</Typography>
<Typography color="textSecondary" gutterBottom variant="body2">
Make your own diagram!
</Typography>
</Box>
<Box
sx={{
py: 2,
}}
>
{/* <div
dangerouslySetInnerHTML={{
__html:
"<img style='cursor:pointer;' title='Click to edit image' onclick='DiagramEditor.editElement(this);' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAA9CAYAAACJM8YzAAADT3RFWHRteGZpbGUAJTNDbXhmaWxlJTIwaG9zdCUzRCUyMmVtYmVkLmRpYWdyYW1zLm5ldCUyMiUyMG1vZGlmaWVkJTNEJTIyMjAyMS0wMS0xMVQxMCUzQTQxJTNBMzQuMjQ4WiUyMiUyMGFnZW50JTNEJTIyNS4wJTIwKE1hY2ludG9zaCUzQiUyMEludGVsJTIwTWFjJTIwT1MlMjBYJTIwMTFfMV8wKSUyMEFwcGxlV2ViS2l0JTJGNTM3LjM2JTIwKEtIVE1MJTJDJTIwbGlrZSUyMEdlY2tvKSUyMENocm9tZSUyRjg3LjAuNDI4MC44OCUyMFNhZmFyaSUyRjUzNy4zNiUyMiUyMGV0YWclM0QlMjJtNXI1QVhFdDE3eWx2WWlEWXo5UyUyMiUyMHZlcnNpb24lM0QlMjIxNC4xLjklMjIlMjB0eXBlJTNEJTIyZW1iZWQlMjIlM0UlM0NkaWFncmFtJTIwaWQlM0QlMjJlbVlSU0REUmtEUDJZZDNFWnkzciUyMiUyMG5hbWUlM0QlMj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KBGTleJrbwMAALS0tuH79+p9k/P98q5EAbmxsHDiLj3JKnf70HE4QbGxsRCG1sLAAU1NTlccomp8esajYUwKkflRH2Nvb48yZM3u3QAUj/QHHzs5OFJLK9uv4P0r378n/kyRrQxhf4x8HGLIEq4EhM2QJHJBAIieZIUvggAQSOckMWQIHJJDISWbIEjgggUROMkOWwAEJJHKSGbIEDkggkZPMkCVwQAKJnGSGLIEDEkjkJDNkCRyQQCInmSFL4IAEEjnJDFkCBySQqJJkCfRKK1GhUOz+BbaftLWDFNYjAAAAAElFTkSuQmCC'/>",
}}
/> */}
<img
alt="Click to edit image"
onClick={EditDiagram.DiagramEditor.editElement(this)}
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAA9CAYAAACJM8YzAAADT3RFWHRteGZpbGUAJTNDbXhmaWxlJTIwaG9zdCUzRCUyMmVtYmVkLmRpYWdyYW1zLm5ldCUyMiUyMG1vZGlmaWVkJTNEJTIyMjAyMS0wMS0xMVQxMCUzQTQxJTNBMzQuMjQ4WiUyMiUyMGFnZW50JTNEJTIyNS4wJTIwKE1hY2ludG9zaCUzQiUyMEludGVsJTIwTWFjJTIwT1MlMjBYJTIwMTFfMV8wKSUyMEFwcGxlV2ViS2l0JTJGNTM3LjM2JTIwKEtIVE1MJTJDJTIwbGlrZSUyMEdlY2tvKSUyMENocm9tZSUyRjg3LjAuNDI4MC44OCUyMFNhZmFyaSUyRjUzNy4zNiUyMiUyMGV0YWclM0QlMjJtNXI1QVhFdDE3eWx2WWlEWXo5UyUyMiUyMHZlcnNpb24lM0QlMjIxNC4xLjklMjIlMjB0eXBlJTNEJTIyZW1iZWQlMjIlM0UlM0NkaWFncmFtJTIwaWQlM0QlMjJlbVlSU0REUmtEUDJZZDNFWnkzciUyMiUyMG5hbWUlM0QlMjJQYWdlLTElMjIlM0VqWkxOVG9Rd0VJQ2ZwbGV6MEloNkZkZjE0Z2tUejVXT3ROblNrbElXOE9sdDdWUm9OaVplWU9hYjZmd1RX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QHHzs5OFJLK9uv4P0r378n/kyRrQxhf4x8HGLIEq4EhM2QJHJBAIieZIUvggAQSOckMWQIHJJDISWbIEjgggUROMkOWwAEJJHKSGbIEDkggkZPMkCVwQAKJnGSGLIEDEkjkJDNkCRyQQCInmSFL4IAEEjnJDFkCBySQqJJkCfRKK1GhUOz+BbaftLWDFNYjAAAAAElFTkSuQmCC"
/>
{/* <Tester /> */}
</Box>
<Box sx={{ my: 3 }}>
<Typography color="textPrimary" variant="h4">
Scenario
</Typography>
<Typography color="textSecondary" gutterBottom variant="body2">
Enter scenarios
</Typography>
</Box>
<SetScenario countList={countList} />
<Box
sx={{
alignItems: "center",
display: "flex",
ml: -1,
}}
></Box>
{Boolean(formik.touched.policy && formik.errors.policy) && (
<FormHelperText error>{formik.errors.policy}</FormHelperText>
)}
<Box
sx={{
py: 2,
display: "flex",
justifyContent: "flex-end",
justifyContent: "space-between",
}}
>
<Box>
<Button
color="primary"
disabled={formik.isSubmitting}
size="large"
variant="contained"
onClick={AddScenario}
sx={{
marginRight: 1,
}}
>
Add Row
</Button>
<Button
color="primary"
disabled={formik.isSubmitting}
size="large"
variant="contained"
onClick={DeleteScenario}
>
Delete Row
</Button>
</Box>
<NextLink href="/requirements" passHref>
<Button
color="primary"
disabled={formik.isSubmitting}
size="large"
type="submit"
variant="contained"
>
Submit
</Button>
</NextLink>
</Box>
</form>
</Container>
</Box>
</>
);
};
WorkArea.getLayout = (page) => <DashboardLayout>{page}</DashboardLayout>;
export default WorkArea;

Related

Pass control prop to child component in react hook form

I'm trying to pass the control prop to my custom component that comes from react-hook-form but it tells that the control is undefined
I did the same thing written in document. I used FormProvider like this:
<FormProvider {...methods}>
<form
style={{
height: "auto",
width: "90%",
padding: "2em",
paddingTop: "0",
textAlign: "center",
backgroundColor: "white",
borderRadius: "10px",
}}
onSubmit={methods.handleSubmit((data) => console.log(data))}
>
<IconButton
color="error"
onClick={() => setRecordControl({ stat: "" })}
>
<Cancel fontSize="large" />
</IconButton>
<h3 style={{ marginBottom: "10px", textAlign: "center" }}>
saving records
</h3>
{filtered.ListColumnInfo.map(
(detail) =>
detail.VisibleColumn && (
<div key={uuidV4()}>
<CustomTextBoxComponent
filtered={detail}
/>
</div>
)
)}
<Button
variant="contained"
fullWidth
color="success"
sx={{ mt: "1em" }}
type="submit"
>
save
</Button>
</form>
</FormProvider>
and I tried to retrieve the control inside of my CustomTextBoxComponent like this:
const CustomTextBoxComponent = ({ filtered }) => {
const { control } = useFormContext();
return (
<Controller
name="input"
render={({ field }) => (
<TextField
fullWidth
placeholder={
filtered.ElsRecord.PersianName !== ""
? filtered.ElsRecord.PersianName
: filtered.ElsRecord.Name
}
sx={{ marginBlock: "1em" }}
{...control}
{...field}
/>
)}
defaultValue=""
/>
);
};
it didn't work. always says the method is null
the picture of Error
how can I solve it?

How to declare one button in a react component and update the title of it in another?

I was wondering if anyone could tell me the best way to dyamically change the button title I'm using in the PopUp component to change the title to 'login' or 'signup' depending on what component I'm passing into the NavBar?
I'm returning a and form into each PopUp component in the navbar as children but have gotten a bit stuck on how to get the title to change. Any help would be much appreciated.
const BootstrapDialog = styled(Dialog)(({ theme }) => ({
"& .MuiDialogContent-root": {
padding: theme.spacing(2),
},
"& .MuiDialogActions-root": {
padding: theme.spacing(1),
},
}));
const BootstrapDialogTitle = (props) => {
const { children, onClose, ...other } = props;
return (
<DialogTitle sx={{ m: 0, p: 2 }} {...other}>
{children}
{onClose ? (
<IconButton
aria-label="close"
onClick={onClose}
sx={{
position: "absolute",
right: 8,
top: 8,
color: (theme) => theme.palette.grey[500],
}}
>
<CloseIcon />
</IconButton>
) : null}
</DialogTitle>
);
};
BootstrapDialogTitle.propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
};
export function PopUp(props) {
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div>
<Button color="inherit" onClick={handleClickOpen}>
SignUp
</Button>
<BootstrapDialog
onClose={handleClose}
aria-labelledby="customized-dialog-title"
open={open}
>
<BootstrapDialogTitle
id="customized-dialog-title"
onClose={handleClose}
>
<Logo />
</BootstrapDialogTitle>
<DialogContent dividers>{props.children}</DialogContent>
</BootstrapDialog>
</div>
);
}
export default function NavBar() {
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="fixed">
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="menu"
sx={{ mr: 2 }}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
<Logo />
</Typography>
<PopUp>
<Login />
</PopUp>
<PopUp>
<SignUp />
</PopUp>
<Button color="inherit">About</Button>
</Toolbar>
</AppBar>
</Box>
);
}

Footer for page with Material-UI Drawer

So, there is a similar question on Stack Overflow, but that's not what I need. I want to make a regular full width footer at the bottom of the page. Here is the code for it, borrowed straight from Material-UI Drawer. Whatever I try to add here, I can't make my footer to appear at all. Once I managed to make it appear but it still was under the drawer, so I could only see a part of it to the right of the drawer.
const drawerWidth = 240;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: 'flex',
},
appBar: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
// necessary for content to be below app bar
toolbar: theme.mixins.toolbar,
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing(3),
},
}),
);
export default function PermanentDrawerLeft() {
const classes = useStyles();
return (
<div className={classes.root}>
<CssBaseline />
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<Typography variant="h6" noWrap>
Permanent drawer
</Typography>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
anchor="left"
>
<div className={classes.toolbar} />
<Divider />
<List>
{['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
<List>
{['All mail', 'Trash', 'Spam'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Typography paragraph>
Text
</Typography>
<Typography paragraph>
Text
</Typography>
</main>
</div>
);
}

React and Material UI: how can I expand only one single card

I'm using React and Material UI in order to show some mapped cards mapped. When I try to expand a card, all the cards are expanded at the same time. I figured out that I have to pass an index inside my "handleExpandClick" function, but still not working. Maybe I did it some kind of typo.
I found this question Expand one card on click that regards the same problem, but seems not to be applied to my situation.
Here my piece of code:
const useStyles = makeStyles(theme => ({
card: {
maxWidth: 345,
marginBottom: 15
},
media: {
height: 0,
paddingTop: "56.25%" // 16:9
},
expand: {
transform: "rotate(0deg)",
marginLeft: "auto",
transition: theme.transitions.create("transform", {
duration: theme.transitions.duration.shortest
})
},
expandOpen: {
transform: "rotate(180deg)"
},
avatar: {
width: 90
},
root: {
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
"& > *": {
margin: theme.spacing(0.5)
}
},
list: {
width: 200
}
}));
const ItininerariesList = ({ itineraries, activities }) => {
const classes = useStyles();
const [expanded, setExpanded] = React.useState(false);
let path = window.location.pathname;
let currentId = path.substring(path.lastIndexOf("/") + 1);
const itinerariesPerCity = itineraries.filter(
itiner => itiner.city_id === currentId
);
const handleExpandClick = () => {
setExpanded(!expanded);
};
return (
<Fragment>
{itinerariesPerCity.map((itinerary, i) => (
<Card className={classes.card} key={itinerary._id}>
<CardHeader
avatar={
<Grid
container
direction="column"
justify="flex-start"
alignItems="center"
className={classes.avatar}
>
<Avatar
aria-label="user"
alt={itinerary.profile_name}
src={itinerary.profile_img}
>
<PersonIcon />
</Avatar>
<Typography variant="caption" component="p">
{itinerary.profile_name}
</Typography>
</Grid>
}
action={
<IconButton aria-label="settings">
<MoreVertIcon />
</IconButton>
}
title={itinerary.title}
subheader={itinerary.sub_title}
/>
<CardContent>
</CardContent>
<CardActions disableSpacing>
<IconButton aria-label="add to favorites">
<FavoriteIcon />
</IconButton>
<IconButton aria-label="share">
<ShareIcon />
</IconButton>
<IconButton
className={clsx(classes.expand, {
[classes.expandOpen]: expanded
})}
onClick={() => handleExpandClick()}
aria-expanded={expanded}
aria-label="show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expanded} timeout="auto" unmountOnExit>
<CardContent>
<ActivitiesList
activities={activities}
itineraryId={itinerary._id}
/>
</CardContent>
</Collapse>
</Card>
))}
</Fragment>
);
};
export default ItininerariesList;
Any suggestions or guidance would be greatly appreciated. Thank you in advance.
In the expand handler you indeed have to pass the index. And also use it in the state.
Something like it:
const [expandedId, setExpandedId] = React.useState(-1);
...
const handleExpandClick = (i) => {
setExpandedId(expandedId === i ? -1 : i);
};
...
<CardContent />
<CardActions disableSpacing>
<IconButton aria-label="add to favorites">
<FavoriteIcon />
</IconButton>
<IconButton aria-label="share">
<ShareIcon />
</IconButton>
<IconButton
onClick={() => handleExpandClick(i)}
aria-expanded={expandedId === i}
aria-label="show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expandedId === i} timeout="auto" unmountOnExit>
<CardContent>
<div>ActivitiesList</div>
</CardContent>
</Collapse>
Here is a working example: https://codesandbox.io/s/eloquent-sara-wswrn

Search bar producing a synthetic event

I have a search bar component that should take the value of the input, however I am using useState for my getters and setters and i am a bit confused as it is reported an error of
Below is my component, can you spot the erorr?
const SuppliersNavBar = (props) => {
const { classes } = props;
const [search, setSearch] = useState();
const updateSearch = (event) => {
setSearch({ search: event.target.value });
console.log(event);
};
return (
<Fragment><Fab className={classes.addCircle} style={{ float: 'right',
marginRight: 10, marginBottom: 10, backgroundColor: '#3B70BC', color:
'white' }} onClick={() => { this.props.history.push('/'); }}
id="addCircle" ><Add /></Fab>
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Grid container direction="row"
justify="flex-start"
alignItems="center">
<Grid item xs={12} sm={6} md={3}>
<div className={classes.grow} />
<div className={classes.search} aria-label="search bar">
<div className={classes.searchIcon}>
<Search id="searchIcon" />
</div>
<InputBase
aria-label="search bar"
value={search}
onChange={updateSearch.bind(this)}
placeholder="Search"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
/>
</div>
</Grid>
</Grid>
</Toolbar>
</AppBar>
</div>
</Fragment>
);
};
Events in React are handled through object pooling meaning that events aren't readable through the console. You can call event.persist() and you will be able to see it. Please look at this page for further information. https://reactjs.org/docs/events.html

Categories

Resources