Error: onSubmit doesn't work on reactjs jsx render method - node.js

I'm trying to create a form inside a react component on node server but my onSubmit attr isn't being compiled. any thoughts why?
Here is my code:
/** #jsx React.DOM **/
var React = require('react');
module.exports = UserForm = React.createClass({
handleSubmit: function (e) {
e.preventDefault();
console.log("teste");
},
render : function () {
return (
<div className="container">
<form onSubmit= { this.handleSubmit } className="section">
<button className="btn waves-effect waves-light" type="submit">
Entrar
<i className="mdi-content-send right"></i>
</button>
</form>
</div>
)
}
});
and the output for this rendered code is this :
<div class="container" data-reactid=".1vxqgp72xa8" data-react-checksum="-1342114635">
<form class="section" data-reactid=".1vxqgp72xa8.0">
<button class="btn waves-effect waves-light" type="submit" data-reactid=".1vxqgp72xa8.0.1">
<span data-reactid=".1vxqgp72xa8.0.1.0">Entrar</span>
<i class="mdi-content-send right" data-reactid=".1vxqgp72xa8.0.1.1"></i>
</button><div class="preloader-wrapper big active" data-reactid=".1vxqgp72xa8.0.2">
</form>
</div>
this may be a silly error, can someone help me finding it?
THanks you all

Simple enough, you aren't providing a callback. It should look like this:
<form onSubmit={ this.handleSubmit } className="section">
Edit:
After a little discussion in the comments, it became clear you weren't mounting the app on the front-end after delivering the server rendered html to the browser. After the page has loaded call this:
React.render(React.createElement(UserForm, {}), domElement);

Related

How to show a popup modal on page load in React js functional component

How to show a popup modal on page load in React js functional component.basically when the page loads the popup or modal should be visible automatically without any click
Most modals will have a prop to specify whether or not the modal should be open. You can simply set this to true on initialization.
Consider an example using a Dialog from the React UI library MUI:
const SimpleDialog = (props) =>
{
const [open, setOpen] = useState(true)
return (
<Dialog open = {open}>
<DialogTitle>Title</DialogTitle>
<DialogContent>...</DialogContent>
</Dialog>
)
}
The open prop of the Dialog is based on the value of the state variable, which is initialized as true. You can change this value as needed through various Dialog actions. To learn more about MUI Dialogs, see the docs.
For information on useState, see the React docs.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
modalState: true
};
this.handleShow = this.handleShow.bind(this);
}
handleShow() {
this.setState({ modalState: !this.state.modalState });
}
render() {
return (
<div>
<div className={"modal fade" + (this.state.modalState ? " show d-block" : " d-none")} tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">My Profile</h5>
<button type="button" className="close" onClick={this.handleShow}>
<span>×</span>
</button>
</div>
<div className="modal-body">...</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={this.handleShow}>Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
ReactDOM.render(, document.getElementById('root'));
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Cannot POST /admin Error return in web browser

I want to update my images on the blog page. but I got an error in the web browser like
Cannot POST /admin/portfolio/609911b1fba77be609396747/edit_cover
here is edit_cover.ejs file code and I use post method to submit images in the database
<%-include('./partials/header')%>
<div class="container-fluid">
<h1 class="text text-primary">Change Porfolio Cover Image Section</h1>
<div class="card shadow mb-4">
<div class="card-header">
<form action="/admin/portfolio/<%=work._id%>/edit_cover" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlFile1">Cover</label>
<input type="file" name="cover" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile2">Snaps of Project</label>
<input class="form-control-file" name="images" type="file" id="exampleFormControlFile2" multiple>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" >Update</button>
</div>
</form>
</div>
<div class="card-body">
<div class="table-responsive">
</div>
</div>
</div>
My router.js file code is here and two lines of code in here one is get request and other is for post
router.get('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
here is my backend controller and code for images updating
exports.portfolio_edit_cover = async function(req,res){
res.render('server/edit_cover',{
work : await workCollection.findOne({_id: objectId(req.params.id)})
})
}
exports.portfolio_edit_cover_post = function(req,res){
let uploadImages = new Work(req.body, req.files, req.params.id)
console.log(req.files)
uploadImages.up().then((result)=>{
res.redirect('/admin/portfolio',{
work : result
})
}).catch(()=>{
res.send('404')
})
}
and lastly this all about my model codes. in the following code is just for how update my data onto databae
Work.prototype.up = function(){
return new Promise(async(resolve,reject)=>{
await workCollection.updateOne({_id : objectId(this.id)}, {$set :
{
images : this.images
}
}
)
resolve()
})
}
module.exports = Work
in edit_cover.js file it has path like
action="/admin/portfolio/<%=work._id%>**/edit_cover**" and router.js it's like
router.get('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
both of these need to have the same path; everything is fine but at last segment, it should be /cover_edit

Submitting a form results to a url segment undefined in NodeJs

I am setting up a simple form submission, when I submit the form the url becomes undefined
This is the view: http://localhost:3000/dashboard/tours/categories
router.get('/tours/categories', function (req, res) {
res.render('agents/tourcategories', {
page_link: 'wishlist'
});
});
This is the form:
<form method="POST" action="/dashboard/tours/categories" >
<div class="box_general padding_bottom">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="categoryname" class="form-control" placeholder="e.g Hiking">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary pull-left" type="button" data-
dismiss="modal">Cancel</button>
<button id="" type="submit" class="btn btn-primary" >Save</a>
</div>
</form>
when I submit the form tne url changes to: `
http://localhost:3000/dashboard/tours/undefined
router.post('/tours/categories',function (req, res) {
console.log("We are here");
const category = new CategoriesDB({
categoryname: req.body.categoryname,
addedby: res.locals.useremail
});
// Save a Customer in the MongoDB
CategoriesDB.save(function (err) {
if(err){
console.log(err);
return;
}else{
res.redirect('/tours/categories');
}
})
});
I realy dont know where the undefined came from, I have checked everything seems to be okay. It keeps popping up in the url everythime i submit the form
`
From the snippets of the code you have posted, It might be because u have not used the middleware
router.all("/dashboard*");
But if u have used that and the GET request is working but not the POST then u will need to post more snippets of your code, mainly the middleware you defined to handle the routes

TypeError: this.props.delItemRow is not a function for deleting item

I have put in my whole day tried every method but to vain my efforts. I am learning React how to make work a delete functionality but then to vain .
A simple TO-DO list where the delete is not working. I dont know where i'm doing wrong.
Here are the js files: display and addList, which is parent to display. Using props the parent function is not being called.
display.js
class DisplayList extends Component{
delRow(en){
this.props.delItemRow(en);
}
render(){
return(
// console.log("check"+this.props.list),
<div>
<h4>DisplayList</h4>
<ul>
{this.props.list.map((item)=>(<li key={item}>{item} <button onClick={this.delRow.bind(this,item)}>D</button> </li>))}
</ul>
</div>
);} }
export default DisplayList;
addlist.js
class AdList extends Component{
constructor(props){
super(props);
this.state={value:'',disArrList:[]}
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
this.delItemRow=this.delItemRow.bind(this);
this.updateItemRow=this.updateItemRow.bind(this);
}
delItemRow(itemName)
{this.setState({disArrList:this.state.disArrList.filter(e1=>e1!==itemName)};
}
handleChange(e){
this.setState({value:e.target.value});
}
handleSubmit(e){
e.preventDefault();
//alert("submit"+this.state.value);
let mycolletion=this.state.disArrList.concat(this.state.value);
this.setState({disArrList:mycolletion});
}
render(){
return(
<div>
<div className="Todo">
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange}/>
<input type="submit" value="Add" />
</form>
</div>
<div>
<DisplayList list={this.state.disArrList} removeItem={this.delItemRow} updateItem={this.updateItemRow}/>
</div>
</div>
);}}
export default AdList;
Thank you any help would be appreciated
The prop you are passing is called removeItem, so you have to change it in your snippet.
display.js
delRow(en){
this.props.removeItem(en);
}
render(){
return(
<div>
<ul>
{this.props.list.map((item)=>(<li key={item}>{item} <button onClick={this.delRow.bind(this,item)}>D</button> </li>))}
</ul>
</div>
);
}
In addlist.js you pass this.delItemRow in props as removeItem,
so in display.js you can access to delItem with this.props.removeItem
if you want to access it, with this.props.delItem in display.js simply you can change it into:
<DisplayList list={this.state.disArrList} delItemRow={this.delItemRow} updateItem={this.updateItemRow}/>

Reading mongodb to HBS (handlebars) template

I am trying to display data from my mongodb backend to an hbs template by trying to port over this tutorial. I do not get any errors from the server logs or the console in the browser, but I do not get any data represented on the template. Interestingly enough, however, it is generating html markup. Please help me see the issue.
*Note using express framework (and still learning)
app.js:
app.post("/", function(req, res){
res.render("default", {title:"posts", entries:myRoute.getBlogEntries()});
});
myRoute.js:
exports.getBlogEntries = function(res) {
mongo.connect("mongodb://localhost:27017/myDB", function(err, db){
if(err) { return console.dir(err); }
var collection = db.collection("posts");
collection.find({},{},function(e,docs){
res.render("default", {
"entries" : docs
});
});
});
};
hbs template:
{{#each entries}}
<form method="POST">
<div class="well">
<div class="row">
<div class="col-md-1">
<div>
<button type="submit" value="{{_id}}" class="btn btn-lrg btn-primary" name="voteup" title="Vote post up"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</div>
<div style="text-align:center;padding-right:5px;padding-top:7px;padding-bottom:7px;"><span class="badge">{{voteCount}}</span></div>
<div>
<button type="submit" value="{{_id}}" class="btn btn-lrg btn-danger" name="votedown" title="Vote post down"><span class="glyphicon glyphicon-thumbs-down"></span></button>
</div>
</div>
<div class="col-md-10">
<h4>{{title}}</h4>
<label style="font-weight:normal;font-style:italic">Posted: {{published}}</label>
<div>
{{body}}
</div>
</div>
</div>
</div>
</form>
{{/each}}
Thanks in advance!
I assume you are using the mongodb driver,which you did not specify.
collection.find returns a mongodb cursor , not an array of documents. You can use toArray to get the documents :
collection.find().toArray(function(e,docs){
...
}
I suggest your read the documentation of the library before using it,because you just can guess what an api does.

Resources