score:4
it's usually not a very good idea to have jquery mucking with react components (though jquery + react can play nice with each other for certain tasks); we are running a large scale react application and have spent many hours removing instances of this from our early days.
in terms of saving the comments, you need a new endpoint to handle that functionality, it should look almost exactly like app.post('/api/comments')
except instead of getting data
from reading the file, it should get data from req.body
, which is the data posted to it. to keep the same url this.props.url
you could set it up as a patch endpoint: app.patch('/api/comments' ...)
. i'll leave that implementation up to you. the react save functionality should happen like this: the comment
component should use state to manage it's...state. clicking "edit" should switch that state to have the contenteditable
set to true, "edit" become "save", etc. the actual saving part should be defined in the parent component commentbox
and should be passed down to the comment
component. here is a basic idea of the changes you should make to allow editing, it's 100% untested but hopefully helps out some.
// changes to comment component
var comment = react.createclass({
getinitialstate: function() {
return {
contenteditable: false,
buttontext: 'edit',
text: this.props.text
};
},
handlebutton: function() {
var commenttag = this.refs.comment;
// if the component is currently editable and the text is different from the original, save it
if (this.state.contenteditable && commenttag.textcontent != this.state.text) {
this.props.onupdatecomment(this.props.id, commenttag.textcontent);
}
// invert current contenteditable state save => edit or edit => save
var editable = !this.state.contenteditable;
this.setstate({
contenteditable: editable,
// update the state to reflect the edited text
text: commenttag.textcontent,
// change button text based on editable state
buttontext: editable ? 'save' : 'edit'
});
},
render: function() {
return (
<div classname="comment">
<h2 classname="commentauthor">{this.props.author}</h2>
<p ref="comment" contenteditable={this.state.contenteditable}>{this.state.text}</p>
<button onclick={this.handlebutton}>{this.state.buttontext}</button>
</div>
);
}
});
// changes to commentlist
var commentlist = react.createclass({
render: function() {
var commentnodes = this.props.data.map(function(comment) {
return <comment onupdatecomment={this.props.onupdatecomment} {...comment} />
});
return (
<div classname="commentlist">
{commentnodes}
</div>
);
}
});
// changes to commentbox
var commentbox = react.createclass({
loadcommentsfromserver: function() {
$.getjson(this.props.url)
.then(function(newcomments) {
this.setstate({ data: newcomments });
}.bind(this))
.fail(function(xhr, status, err) {
console.error(this.props.url, status, err.tostring());
});
},
handlecommentsubmit: function(comment) {
var comments = this.state.data;
comment.id = date.now();
var newcomments = comments.concat([comment]);
this.setstate({data: newcomments});
$.post(this.props.url, comments)
.then(function(data) {
this.setstate({ data: data });
}.bind(this))
.fail(function(xhr, status, err) {
this.setstate({ data: comments });
console.error(this.props.url, status, err.tostring());
}.bind(this));
},
onupdatecomment: function(id, comment) {
// clone state, we don't want to alter this directly
var newdata = this.state.data.slice(0);
newdata.foreach(function(item) {
if(item.id === id) {
item.text = comment;
}
});
$.ajax({
url: this.props.url,
datatype: 'json',
method: 'patch',
data: newdata
}).then(function(data) {
this.setstate({ data: data });
}.bind(this));
},
getinitialstate: function() {
return {data: []};
},
componentdidmount: function() {
this.loadcommentsfromserver();
setinterval(this.loadcommentsfromserver, this.props.pollinterval);
},
render: function() {
return (
<div classname="commentbox">
<h1>comments</h1>
<commentlist data={this.state.data} />
<commentform oncommentsubmit={this.handlecommentsubmit} />
</div>
);
}
});
Source: stackoverflow.com
Related Query
- ReactJS for editing comments
- Listen to keypress for document in reactjs
- Expected corresponding JSX closing tag for input Reactjs
- TypeScript interface signature for the onClick event in ReactJS
- react-intl vs react-i18next for ReactJS internationalization (i18n)
- MVVM architectural pattern for a ReactJS application
- Media query syntax for Reactjs
- reactjs : ShouldComponentUpdate for states
- Best practice for ReactJS form components
- React tutorial - how do I start the node server for a reactJs application?
- ReactJS async, wait for results
- ReactJS - How can I set a value for textfield from material-ui?
- Reactjs console error ([HMR] Waiting for update signal from WDS...)
- Assign a value to a variable in JSX for ReactJS
- ReactJS local server crashes after editing file in Emacs even without saving
- Re-render Reactjs components for print
- Object.entries() alternative for Internet Explorer and ReactJS
- Implementing Facebook comments plugin in ReactJS app
- Facebook ReactJS and Zurb Foundation for Apps?
- Reactjs animate replace: How to wait for fade out before adding content to fade in?
- ReactJS writing stateless function comments
- Why doesn't ReactJS autogenerate keys for dynamic children?
- ReactJS components for PDF export, Excel export and print
- How can I achieve view-model separation in a Javascript component for editing HTML?
- Why getDerivedStateFromProps does not allow to re-render with the state update? Not a problem for componentWillReceiveProps - ReactJS
- How can I use CSS @media for responsive with makeStyles on Reactjs Material UI?
- Why does hot reloading not work for reactjs visual studio 2019 template
- How to use a proxy for a link with reactjs
- Redux - ReactJS app does not rerender (although JSON.parse for new object)
- ReactJS overriding or editing context along the hierarchy
More Query from same tag
- Dynamic pagination with Scroll in ReactJs
- showing error message returned from server validation in react
- How to access component parameters from app.js in react router
- React Function Components - following parent component state
- Using StorybookJS in a component library package with React as peer dependency
- Why my 'Select' components in react are synchronized together?
- Cant give color background on React Bootstrap
- componentDidUpdate is not firing
- timezone conversion using date-fns
- React Builder tool won't set public url correctly
- Multiplicate values between objects by the index
- Cleanly perform map() over Set collection state but still rerender on state changes?
- get unique values from array but also display the amount of duplicates it had (javascript - reactjs)
- How to display corresponding image from selected item in React using hooks
- How to avoid shapes from changing size and position when deleting previous shape component with same component name? Konva
- Token visibility in Next.js
- Adjusted proxy settings in Create-React-App to get around CORS blocking error and now get an undefined response
- useState is initialized multiple times
- ASP.NET Core 2.1 Web application with React.Aspnet error when running as Docker application
- Making scrollable div in CSS
- How do I conditionally get items from DB using specific value in React(Next.js)?
- Unable to read properties of a property containing the object
- React Typescript - ReactNode type cuts string literals
- repeated data array .map () react
- React : Add / Remove components with buttons : Remove not working
- Values with Redux-Form return null
- Uploading an image using cloudinary, and displaying it to the UI
- Active classnames in menu on a one-page website using GatsbyJS
- React re-write componentWillReceiveProps in useEffect
- React + Bootstrap : cannot map Tabs content