Save Position of react-draggable objects in react - reactjs

I am using react-draggable to drag and drop elements. How should I save the elements positions after dragging.
<div className={classes.section}>
<h5>Create Invoice</h5>
{isEditing ? <Button variant="contained" color="primary">Edit</Button> : <Button variant="contained" color="primary">Update</Button>} </label>
<div id="target" onDrop={this.drop} onDragOver={this.allowDrop}>
<Paper className={classes.paper} >
<form>
<Draggable axis="both" bounds="div" disabled={isEditing}>
<CustomInput select variant="outlined" label="To" helperText="Please select your company"/></Draggable>
<Draggable axis="both" bounds="div" disabled={isEditing}><CustomInput name="invoicenumber" label="Invoice Number"/></Draggable>
<Draggable axis="both" bounds="div" disabled={isEditing}><CustomInput id="Date" label="Issue Date" defaultValue="2019-01-01" type="Date" variant="outlined" InputLabelProps={{shrink:true}}/></Draggable>
<TextField id="Date" defaultValue="2019-01-01" type="Date" variant="outlined" InputLabelProps={{shrink:true}}/>
<h5>Item Id</h5> */}
<Draggable axis="both" bounds='div' disabled={isEditing}><CustomInput type="textarea" variant="outlined" label="Description"/></Draggable>
<Draggable axis="both" bounds='Div' disabled={isEditing}>
<CustomInput type="file" variant="outlined" helperText="Attachments" style={{alignContent:"right"}}/>
</Draggable>
</form>
</Paper>
</div>

This is the function for getting the value. Once you get the value then you'll set it a database or localStorage whatever you want.
const eventLogger = (e, data) => {
localStorage.setItem('defaultPosition', { valueX: data.x, valueY: data.y });
};
This function will be called in Dragable by the event onStop.
<Draggable defaultPosition={{ x: 0, y: 0 }} onStop={eventLogger}>
<h2 style={{ cursor: 'grab' }}>
dragable
</h2>
</Draggable>

Related

React Application form data with image uploading field cannot POST to my backend api

First I am trying to post my form data without an image then that data is passed to the backend successfully. then I try to send an image to the backend with form data and then I got an error. image uploading field is a not required field. how I pass the image to the backend with form data.
This is my basic info tab image uploading field
<Grid item xs={6} md={3} sm={4}>
<Controller
name="avatar"
id="avatar"
control={control}
render={({ field }) => (
<TextField
{...field}
className="mt-4 mb-8"
type="file"
onChange={(event) => {
// console.log(event.target.files[0]);
setSelectedImage(event.target.files[0]);
}}
autoFocus
value={selectedImage}
variant="outlined"
size="small"
fullWidth
/>
)}
/>
</Grid>
this is my user.js file return
return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<Root
header={<UserHeader />}
contentToolbar={
<Tabs
value={tabValue}
onChange={handleTabChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
classes={{ root: 'w-full h-64' }}
>
<Tab className="h-64" label="Basic Info" />
// <Tab className="h-64" label="User Images" />
</Tabs>
}
content={
<div className="p-16 sm:p-16 max-w-2xl">
<div className={tabValue !== 0 ? 'hidden' : ''}>
<BasicInfoTab />
</div>
<div className={tabValue !== 1 ? 'hidden' : ''}>
<ImagesTab />
</div>
{/* <div>
<input type="file" name="file_upload" onChange={onFileChage}/>
</div>
<div>
<button>Submit Data</button>
</div>*/}
</div>
}
innerScroll
/>
</form>
</FormProvider>
);
}
This is my error

Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Select)`, expected a ReactNode

I'm trying to render certain inputs if a variable is true but when the component render displays the warning Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Select)`, expected a ReactNode.
Here is the code of the Material-ui Dialog which receive some props, one of them is the one that I validate to show or not a pair of select inputs.
What I'm doing is validate if the variable is true, show them if not, don't show them.
states...
requests...
onSubmit...
return (
<Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
<Collapse in={open}>
<Alert severity={severity}>{alertMsg}</Alert>
</Collapse>
<DialogTitle>Proceso de factura.</DialogTitle>
<DialogContent>
<Container>
<TextField
autoFocus
margin="dense"
id="vus"
name="vus"
label="Valor unitario de servicio."
fullWidth
variant="outlined"
onChange={handleChange}
value={vus}
/>
<TextField
margin="dense"
id="discount"
name="discount"
label="Descuento"
fullWidth
variant="outlined"
onChange={handleChange}
value={discount}
/>
<TextField
margin="dense"
id="paymentMeth"
name="paymentMeth"
label="Método de pago"
fullWidth
variant="outlined"
onChange={handleChange}
value={paymentMeth}
/>
<TextField
margin="dense"
id="payment"
name="payment"
label="Forma de pago"
fullWidth
variant="outlined"
onChange={handleChange}
value={payment}
/>
{requiresCCP ? (
<>
<Box className={classes.formInputs}>
<FormControl fullWidth>
<InputLabel id="select-vehicle">
Vehículo
</InputLabel>
<Select
labelId="select-vehicle"
id="vehicleSelect"
name="vehicleSelect"
value={vehicle}
label="Vehículo"
onChange={handleChange}
>
{allVehicles.map((vehicle, index) => {
return (
<MenuItem
value={vehicle._id}
key={index}
>
{vehicle.PlateNumber} -{" "}
{vehicle.VehicleName} Modelo{" "}
{vehicle.Model}
</MenuItem>
);
})}
</Select>
</FormControl>
</Box>
<Box className={classes.formInputs}>
<FormControl fullWidth>
<InputLabel id="select-contact">
Contacto
</InputLabel>
<Select
labelId="select-contact"
id="contactSelect"
name="contactSelect"
value={contact}
label="Contacto"
onChange={handleChange}
>
value={contact}
onChange={handleChange}
{allContacts.map((contact, index) => {
return (
<MenuItem
value={contact._id}
key={index}
>
{contact.LastNameFather}{" "}
{contact.LastNameMother}{" "}
{contact.FirstName} -{" "}
{contact.OfficialNumber}
</MenuItem>
);
})}
</Select>
</FormControl>
</Box>
</>
) : (
""
)}
</Container>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancelar</Button>
<Button variant="contained" type="submit">
Completar viaje
</Button>
</DialogActions>
</Box>
);
};```
Children you are passing inside the sectect element is incorrect. Just remove value and onchange from its children as you are already passing them as props
<Select
labelId="select-contact"
id="contactSelect"
name="contactSelect"
value={contact}
label="Contacto"
onChange={handleChange}
>
{allContacts.map((contact, index) => {
return (
<MenuItem
value={contact._id}
key={index}
>
{contact.LastNameFather}{" "}
{contact.LastNameMother}{" "}
{contact.FirstName} -{" "}
{contact.OfficialNumber}
</MenuItem>
);
})}
</Select>
If you are working with dates and passing them down as {item.date}
then instead use {item.date.toLocaleDateString()} or {item.date.toString()}
{item.date.toLocaleDateString()} or {item.date.toString()} - This worked for me
<Select
labelId="select-contact"
id="contactSelect"
name="contactSelect"
value={contact}
label="Contacto"
onChange={handleChange}
{allContacts.map((contact, index) => {
return (
<MenuItem
value={contact._id}
key={index}
>
{contact.LastNameFather.toString()}{" "}
{contact.LastNameMother.toString()}{" "}
{contact.FirstName.toString()} -{" "}
{contact.OfficialNumber.toString()}
</MenuItem>
);
})}
Just add toString()

reactjs pop up opened and closed while re-rendering the parent component

I am trying to simulate the Trello board, with reactjs and signalR (.netCore).
I created the board with list of cards and each card item has card details which is a pop up.
that card details pop up opens when the user clicks on the card title. I am using signalR (Websocket) to make multiusers interact within the same board by listening to an event which re-render the whole board when any user change a card.
The issue happens when :
User A is Opening the pop up modal for task 1 and user B is dragging task 2 from todo card list to the in progress card list for example.
when that action happened the pop up close and open again as the whole trello board was rerendered based on the event that each user is listening to.
How can I fix that opening closing issue with the pop up an keep it open as it's ??
and if the logic is wrong please feel free to inform me!
note: I am using react-beautiful-dnd package for the drag and drop feature.
Trello Board
<DragDropContext
onDragEnd={(result) => {
ondragend(result);
}}
>
<div className="App">
<div>
{
sprintLoading ?
sprints.map((card, index) => (
// our sprints
<TrelloList
sprintType={card.sprintType}
index={index}
listId={card.sprintId}
sprintSchemaId={card.sprintSchemaId}
key={card.sprintId}
title={card.sprintName}
cards={card.tasks}
/>
))
: null
}
</DragDropContext >
);
}
Trello List
useEffect(async () => {
}, [tasks, socketState, trelloRerender]);
return (
<Droppable droppableId={String(listId)} >
{(provided) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
style={styles.container}>
<h4>{title}</h4>
{cards ? cards.map((card, index) =>
(
// our tasks
<TrelloCard
sprintType={sprintType}
listId={listId}
index={index}
cardId={card.taskId}
key={card.taskId}
text={card.taskDescription}
projectId={card.projectId}
userId={card.userId}
sprintId={card.sprintId}
sprintSchemaId={card.sprintSchemaId}
title={card.taskName}
schemaId={card.sprintSchemaId}
groupId={card.groupId}
taskStatus={card.taskStatus}
userName={card.user ? card.user.userName : ''}
taskCreatedDate={card.taskCreatedDate}
taskDueDate={card.taskDueDate}
comments={card.comments}
/>
)) : null}
{provided.placeholder}
</div>
)}
</Droppable>
)
};
Trello card
const { showTaskDetails, setShowTaskDetails } = useContext(ShowTaskDetailsContext);
useEffect(async () => {
await axios.get(`${BACKEND_URL}/tasks/${cardId}`).then(res => {
console.log(res.data.comments);
setCurrentTaskComments(res.data.comments)
console.log(currentTaskComments);
});
}, [rerenderForComments]);
useEffect(async () => {
const sprintId = location.pathname.split('/')[2];
setRerenderforCards(false);
setSprintId(sprintId);
setIsRolledback(false);
await fetchObject(`${BACKEND_URL}/sprintschemas/${sprintSchemaId}`)
.then(res => {
if (res.sprintTaskRollback !== null) {
setIsRolledback(true);
}
})
.catch(err => console.log(err));
}, []);
const handleShowTaskDetails = () => setShowTaskDetails(true);
const handleCloseTaskDetails = () => setShowTaskDetails(false);
return (
<Draggable draggableId={String(cardId)} index={index} key={cardId} >
{provided => (
// as provided.innerdiv need to refer to an action DOM node and card is a material-ui node
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps} >
<Card style={styles.cardContainer} >
{/* testing generic hooks */}
<CardContent>
<Typography component={'div'}
gutterBottom>
<span
// href={`/loboard/${sprintId}`}
style={{ display: "block", fontWeight: "bold" }}
onClick={handleShowTaskDetails}
>
{title}
</span>
<TrelloCardDetails
showTaskDetails={showTaskDetails}
handleCloseTaskDetails={handleCloseTaskDetails}
title={title}
description={text}
comments={currentTaskComments}
assignto={userName}
cardId={cardId}
handleDropDownchanged={handleDropDownchanged}
handleMarkCompleted={handleMarkCompleted}
markCompletedBtnTxt={markCompletedBtnTxt}
markBtnStyle={markBtnStyle}
userId={userId}
setComments={setCurrentTaskComments}
rerenderForComments={rerenderForComments}
setRerenderForcommented={setRerenderForcommented}
/>
{/* onchange == move task to it's new list of cards */}
<Form.Group className="mt-2" controlId="exampleForm.ControlSelect2">
<Form.Row>
<Form.Label column="sm" sm={4}>Move to:</Form.Label>
<Col>
{/* adding default value to reset */}
<Form.Control size="sm" as="select"
onChange={handleDropDownchanged}
defaultValue={'select'}
>
<option disabled value="select">select status</option>
<option value="backlog" name='setBacklog'>backlog</option>
<option value="todo" name='setTodo'>todo</option>
<option value="inprogress" name='setInProgress'>inprogress</option>
<option value="done" name='setInProgress'>done</option>
</Form.Control>
</Col>
</Form.Row>
</Form.Group>
<Form.Group>
<Form.Row>
<Form.Label column="sm" sm={4}>assigned to:</Form.Label>
<Col>
<Form.Control
type="text"
disabled
value={userName} />
</Col>
</Form.Row>
</Form.Group>
<Row>
<Button className={markBtnStyle}
onClick=
{() =>
handleMarkCompleted(cardId)
}
style={{ display: "block" }}
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" className="bi bi-check" viewBox="0 0 16 16">
<path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z" />
</svg>
{markCompletedBtnTxt}
</Button>
</Row>
{/* <Row>
<Col> */}
<span className="text-sm float-right mt-2">
<small title="created at" className="text-muted d-block ">
<BsCalendar /> {taskCreatedDate.split('T')[0]}
</small>
</span>
</Typography>
</CardContent>
</Card>
</div>
)}
</Draggable>
)
Card details component
export const TrelloCardDetails = ({
showTaskDetails,
description,
comments,
title,
handleCloseTaskDetails
, assignto, cardId,
handleDropDownchanged,
handleMarkCompleted,
markBtnStyle,
markCompletedBtnTxt,
userId,
setComments, rerenderForComments,
setRerenderForcommented
}) => {
useEffect(() => {
console.log("card details")
}, [comments]);
return (
<div>
<Modal
show={showTaskDetails}
onHide={handleCloseTaskDetails}>
<Modal.Header closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form.Group className="mt-2" controlId="exampleForm.ControlSelect2">
<Form.Row>
<Form.Label column="sm" sm={4}>Move to:</Form.Label>
<Col>
{/* adding default value to reset */}
<Form.Control size="sm" as="select"
onChange={handleDropDownchanged}
defaultValue={'select'}
>
<option disabled value="select">select status</option>
<option value="backlog" name='setBacklog'>backlog</option>
<option value="todo" name='setTodo'>todo</option>
<option value="inprogress" name='setInProgress'>inprogress</option>
<option value="done" name='setInProgress'>done</option>
</Form.Control>
</Col>
</Form.Row>
</Form.Group>
<Form.Group>
<Form.Row>
<Form.Label column="sm" sm={4}>assigned to:</Form.Label>
<Col>
<Form.Control
type="text"
disabled
value={assignto} />
</Col>
</Form.Row>
</Form.Group>
<Form.Group>
<Form.Row>
<Form.Label column="sm" sm={4}>Description: </Form.Label>
<Col>
<Form.Control style={{ resize: 'none' }} as="textarea" value={description} disabled />
</Col>
</Form.Row>
</Form.Group>
<Row>
<Button
className={markBtnStyle}
onClick=
{() =>
handleMarkCompleted(cardId)
}
style={{ display: "block" }}
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" className="bi bi-check" viewBox="0 0 16 16">
<path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z" />
</svg>
{markCompletedBtnTxt}
</Button>
</Row>
{/* <div style={{marginTop:"20px", backgroundColor: "#e9ecef", opacity: "1", border: "1px solid #ced4da", borderRadius: "5px" }}> */}
<CommentList rerenderForComments={rerenderForComments} setRerenderForcommented={setRerenderForcommented} assignto={assignto} comments={comments} setComments={setComments} taskId={cardId} userId={userId} />
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleCloseTaskDetails}>
Close
</Button>
<Button variant="primary" onClick={handleCloseTaskDetails}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</div >
);
}

How to display data from html response body on textfield or textArea in material UI reactjs?

I have a form. On clicking the 'Evaluate' button, I send a post request. The response of this request is JSON, which I need to display in textField named Output.
How to display data in 'Output' textField?
I just need to display data(which is json in this case) to the text field.
My text field looks like this:
const MyTextField = ({select, values, nullable, min, max, helpertext, ...props}) => {
const [field, meta] = useField(props);
return (
<TextField
select={!!select}
variant="outlined"
margin="dense"
//{...field}
//defaultValue={meta.initialValue}
value={field.value}
error={meta.touched && meta.error}
helperText={(meta.touched && meta.error) ? meta.error : helpertext}
onChange={field.onChange}
onBlur={field.onBlur}
InputProps={{inputProps: {min: min, max: max}}}
{...props}
>
{
values && nullable && values instanceof Array && <MenuItem ><em>None</em></MenuItem>
}
{
values && values instanceof Array && values.map((value, index) => {
return <MenuItem key={value} value={value}>{value}</MenuItem>
})
}
</TextField>
);
};
and form looks like this
return (
<Container fluid className="main-content-container px-4">
<Row noGutters className="page-header py-4">
<PageTitle sm="12" title="Transformer Tester Tool" subtitle="" className="text-center"/>
</Row>
<Paper id="connPageRoot" className={classes.testerRoot}>
<Formik onSubmit={submitEvaluate} initialValues={request}>
<Form>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="json2JsonTransformationConfigDto.template"
name="json2JsonTransformationConfigDto.template"
label="JSLT template"
multiline={true}
rowsMax={4}
fullWidth={true}/>
</div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="inputs.0"
name="inputs.0"
label="Json payload to be tested"
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
<div className={classes.connPageButton}>
<Button type={"submit"} color="primary" variant="contained">Evaluate</Button> </div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="outputs.0"
name="outputs.0"
label="Output"
value={result}
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
</Form>
</Formik>
</Paper>
</Container>
);

Change of input value with state in React JS

I am having 3 text boxes in which users enter values alongwith that I have 3 sliders for which the value is set based on calculation of percentage from the entered values. My problem is I also want to change the text box values based on calculation formulas. So the text box I want them to reflect values with calculation as the slider values change plus user can also type in values.For eg for first textbox I want to calculate value inside with (total-b-c). So with changes in slider values of percentages the values in textboxes should also change. I am unable to do that now-
Here is some supporting code for the same-
const [userValues, setUserValues] = useState({
a: '0',
b: '0',
c: '0',
});
const handleInputChange = (event) =>{
setUserValues({ ...userValues, [event.target.name]: event.target.value });
}
Textboxes-
<div className="container1">
<div className="headingsleft">Enter number of <br></br> invoices</div>
<div>
<h4 style={{fontWeight:500, marginLeft:30,fontSize:19}}>a Invoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" name="a" size="small" className={classes.root} inputProps={{ min: "0" }} variant="outlined" value={userValues.nonedinumber} onChange={handleInputChange} required error={userValues.a=== ""} helperText={userValues.a=== "" ? 'Required' : ' '} ></TextField>
</div>
<div>
<h4 className="headings">b Invoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" name="b" size="small" className={classes.root} inputProps={{ min: "0" }} variant="outlined" value={userValues.b} onChange={handleInputChange} required error={userValues.b=== ""} helperText={userValues.b=== "" ? 'Required' : ' '}/>
</div>
<div>
<h4 style={{fontWeight:500, marginLeft:30,fontSize:19}}>cInvoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" name="c" size="small" className={classes.root} inputProps={{ min: "0" }} variant="outlined" value={userValues.c} onChange={handleInputChange} required error={userValues.c=== ""} helperText={userValues.c=== "" ? 'Required' : ' '}/>
</div>
<div>
<h4 style={{fontWeight:500, marginLeft:30,fontSize:19}}>Total Invoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" size="small" id="total" value={total} disabled variant="outlined" />
</div>
</div>
code for the slider-
const Inputaftercalculate = (props) => {
const classes = useStyles();
return (
<div>
<div className="container2">
<div className="headingsleft">Percentage Distribution
</div>
<div >
<br></br>
<br></br>
<Typography className={classes.slider} id="discrete-slider-always" gutterBottom>
</Typography>
<Slider
defaultValue={20}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-always"
step={10}
marks={marks}
valueLabelDisplay="on"
value={props.a}
disabled
/>
</div>
<div>
<br></br>
<br></br>
<Typography className={classes.slider} id="discrete-slider-always" gutterBottom>
</Typography>
<Slider
defaultValue={20}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-always"
step={10}
marks={marks}
valueLabelDisplay="auto"
value={props.b}
/>
</div>
<div>
<br></br>
<br></br>
<Typography className={classes.slider} id="discrete-slider-always" gutterBottom>
</Typography>
<Slider
defaultValue={1}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-always"
step={10}
marks={marks}
valueLabelDisplay="auto"
value={props.c}
/>
</div>
</div>
</div>
How can I make the input textboxes adjust inside values based on changes in slider values and also let users input in the textbox whenever they need to change values?
First you got get the value and it respective key from the event, then expand it and finally assign the value to the respective key name as shown bellow.
const handleInputChange = e => { const {name, value} = e.target; handleInputChange({ ...userValues, [name]: value, }) }

Resources