Coffee-Reactify Compilation Issue - coffeescript

I'm really hoping someone can help me with this issue because I've searched high and low to no avail and tried everything I can think of. I'm new to ReactJS and Browserify (though I don't think this has anything to do with Browserify) and can't seem to get this code working. I've been following along with the video series "Getting Started With React.js," and section 5.2 introduces Browserify and setting it up properly to work with React. Using plain old JavaScript, I'm able to get it working no problem, but when I try to use Coffee-Reactify and CoffeeScript, everything compiles fine, but when I load the page, I get this error:
"Uncaught TypeError: Cannot read property 'firstChild' of undefined"
When I follow the stack trace, it seems to error out in the findComponentRoot method of React, which I haven't touched. This leads me to believe there's something wrong with my CoffeeScript, but I've compared it line for line with the JavaScript, and aside from the additional "return" statements the CoffeeScript compiler adds, nothing seems too different. If anyone out there can replicate or identify my issue, I'd greatly appreciate it! Here is the code for all of my files, and thank you all very much in advance!
index.jade
doctype html
html
head
meta(charset='utf-8')
title React Tools
link(rel='stylesheet', href='bower_components/bootstrap/dist/css/bootstrap.css')
body
#app
script(src='bower_components/lodash/dist/lodash.js')
script(src='bower_components/react/react.js')
script(src='build/app.js')
app.coffee
MessageBox = require('./MessageBox.cjsx')
reactComponent = React.render(
<MessageBox />,
document.getElementById('app')
)
SubMessage.cjsx
SubMessage = React.createClass
handleDelete: (e) ->
#props.onDelete(#props.message)
propTypes:
message: React.PropTypes.string.isRequired
getDefaultProps: ->
message: "It's good to see you"
render: ->
<div>
{#props.message}
<button onClick={#handleDelete} className='btn btn-danger'>x</button>
</div>
module.exports = SubMessage
MessageBox.cjsx
React = require 'react'
SubMessage = require './SubMessage.cjsx'
MessageBox = React.createClass
deleteMessage: (message) ->
newMessages = _.without(#state.messages, message)
#setState
messages: newMessages
handleAdd: (e) ->
newMessage = #refs.newMessage.getDOMNode().value
newMessages = #state.messages.concat [newMessage]
#setState
messages: newMessages
getInitialState: ->
isVisible: true,
messages: [
'I like the world',
'Coffee flavored ice cream is underrated',
'My spoon is too big',
'Tuesday is coming.',
'I am a banana'
]
render: ->
inlineStyles =
display: if #state.isVisible then 'block' else 'none'
messages = #state.messages.map ((message) ->
<SubMessage message={message} onDelete={#deleteMessage} />
).bind(#)
return (
<div className='container jumbotron' style={inlineStyles}>
<h2>Hello, World</h2>
<input ref='newMessage' type='text' />
<button className='btn btn-primary' onClick={#handleAdd}>Add</button>
{ messages }
</div>
)
module.exports = MessageBox
As a side note, React is partially "working" because the messages array gets mapped to a SubMessage array and displays properly with the delete buttons. So the error seems to be happening at a later point in the cycle. Thanks again!

Wow, what an oversight on my part. It turns out I was loading React from two different places, once as a node module in my coffee/cjsx files and again in my HTML, but from a bower-installed version of React. I can't believe I spent so much time on this, but hopefully my struggle helps somebody else!

Related

Material UI DataGridPro - No Rows Rendered

I have a number of DataGrids in our app.
Running tests with Playwright - Chromium - , sometimes prevents the rows from being rendered.
As can be seen in the screenshot, the rows exist, but just not being rendered.
More details, this mostly happens when running the tests from gitlab, but I have also seen it in the front end. Just rarely.
Anybody have any idea how to fix it?
All the affected Tables have a cell that renders like this:
renderCell: (params: any) => (
<div key={params.row.id} className="action_list_element">
{params.row.actionFile
.filter(
(af: ActionFile) =>
af?.actionFileType === ActionFileType.Output
)
.map((af: ActionFile, index: Number) => {
if (af?.file) {
return (
<div
className="no_line_hight"
key={params.row.id + index}
>
<b>
<FileIcon
fileName={af?.file.name}
isValid={af?.file.isValid}
fontSize={"small"}
/>{" "}
<a
href={
"/activity/" +
params.row.pmxActivity.id +
encodeURIComponent("/" + af?.file.absolutePath) +
encodeURIComponent(
"?versionId=" + af?.file.versionId
)
}
>
{af?.file.absolutePath}
</a>
</b>{" "}
({af?.file.revision}) -{" "}
{af?.file.isValid ? "valid" : "not valid"}
</div>
);
} else {
return "";
}
})}
</div>
),
Tried upgrading both Playwright and MUI to the lates version. Did not work.
Also tried to reproduce with my browser, but it went on fine.
It seams it appeared because we were running our test with a headless browser.
https://mui.com/x/react-data-grid/virtualization/
The Documentation explained what was happening, and how to fix it.

Image and CSS links broken after requesting a single doc from mongoDB via mongoose

Hello everyone finding my question.
I am reaching out to this community in the hope that you can help with a problem I am experiencing with Mongoose/EJS.
Just like to say before I explain the issue. I am a newbie so the question may seem simple to most and poorly explained, so apologies for that.
So the problem is that I am trying to display a product details page by using the mongoDB :id via mongoose.
So the data returns to the browser ok but the CSS and IMAGE links are broken. To makes things even more frustrating, the links works perfectly well on all other pages!
On using Morgan I can see that the problem is with their Paths.
The /products/:id path used for the product retrieval from DB is also being prepended to the paths of the CSS and image files, which IS not the intention, and so rendering the paths incorrectly, hence broken links.
I think I hope I have included all the files that I think are required to understand the problem fully, but happy to provide further code if req'd.
Thank you for taking the time to read this and I look forward to a bigger brain coming to the rescue.
Cheers!
const express = require("express");
const app = express();
const Morgan = require("Morgan");
const mongoose = require("mongoose");
const Product = require("./models/product");
const dbURI =
"mongodb+srv://xxxxxx#xxxxx/test-db/retryWrites=true&w=majority";
mongoose
.connect(dbURI)
.then((result) => app.listen(3000),
console.log("connected to mongodb (products) & listening for requests on port: 3000"))
.catch((err) => console.log(err));
// templating engine
app.set("view engine", "ejs");
// middleware and static files
app.use(express.static(__dirname + "/public"));
app.use(Morgan("dev"));
app.use(express.urlencoded({ extended: true }));
=======================================================================
**// details.ejs**
<%- include('./partials/head.ejs') %>
<body>
<main class="body-main">
<!-- ========== Header =============->
<!-- <%- include('./partials/navbar.ejs') %> →
<div class="promotion-panel-lower">
<h1><%=product.title %></h1>
<div class="promo-grid-item">
<div class="product-name">
<%=product.title %>
</div>
<img src=./images/<%=product.img %> alt=<%=product.title %> class="photo" />
<h4 class="prices-from">prices from:<%=product.price %></h4>
</div>
</div>
<!-- =========== footer ============ -->
<%- include('./partials/footer.ejs') %>
=======================================================================
// DOC DETAIL REQUEST
app.get("/products/:id", (req, res) => {
const id = req.params.id;
Product.findById(id)
.then((result) => {
res.render("details", { title: "Details", product: result });
})
.catch((err) => {
throw err;
}); });
=======================================================================
// Terminal
// it should look like this
GET /products/62004ee85f4bcd160b832540 304 282.060 ms - -
GET /css/css-reset.css 404 7.488 ms - 17548
GET /css/style.css 404 6.081 ms - 17548
GET /images/backpack2.jpg 404 7.840 ms - 17548
// BUT here’s the result. i.e. /products/ included to my PUBLIC path CSS and images >
rendering those links obsolete
GET /products/62004ee85f4bcd160b832540 304 282.060 ms - -
GET /products/css/css-reset.css 404 7.488 ms - 17548
GET /products/css/style.css 404 6.081 ms - 17548
GET /products/images/backpack2.jpg 404 7.840 ms - 17548
=======================================================================
I haven't looked at all your code in detail.
For starters, have you tried removing the dot in front of the slash in <img src=./images/<%=product.img %>? Try this: <img src=/images/<%=product.img %>.
Your images folder seems to me to be in the root of your public folder and it would make sense to write / rather than ./.

Vscode cant find function defined in contextBridge.exposeInMainWorld

I just started modifying the electron-react-boilerplate project and tried doing the following:
In the App.tsx file I added a button:
const ping = () => {
electron.ipcRenderer.myAwesomePing('Hello world!');
};
const Hello = () => {
return (
<div>
...
<button type="button" onClick={() => ping()}>
Ping!
</button>
...
</div>
);
};
And in the preload.js file, I added the corresponding call for myAwesomePing:
contextBridge.exposeInMainWorld('electron', {
ipcRenderer: {
myAwesomePing(text) {
ipcRenderer.send('ipc-example', text);
},
When I run the code, everything seems to work fine and I receive the ping through the context-bridge on the main process.
But, visual studio code keeps complaining, that it
Cannot find name 'electron'. Did you mean 'Electron'?
inside App.tsx.
Is this because I am missing something or just a bug in vscode? Is there maybe a build step necessary to create the connection?
ERB recently added support for globally exposed variables via preload:
https://github.com/electron-react-boilerplate/electron-react-boilerplate/blob/main/src/renderer/preload.d.ts
Copy and paste the file into your project and it should just work.

ng-click and ngRouting on mobile devices

I am completely new to Angularjs and haven’t been doing any code for ages. I started setting up my website again with Angularjs. I have a main page and an about page, to which the user gets via ngRoute on ng-click (or hitting space). Once on the about page, the user can go back by clicking somewhere on the page and so on.
App.js
var app = angular.module("MyApp", ["ngRoute"]);
app.config(function($locationProvider, $routeProvider) {
$routeProvider
.when("/teaser", {
controller:"teaserCtrl",
templateUrl:'teaser.html'
})
.when("/about", {
controller:"aboutCtrl",
templateUrl: "about.html"
})
.otherwise({
redirectTo:"/teaser"
})
});
app.controller("mainCtrl", function($scope, $http, $location) {
$scope.v = {
inverted: false,
display: true,
offwhite: true,
}
$scope.$on("space", function() {
if ($scope.v.teaser) {
$location.path("/about")
$scope.v.teaser = false
} else {
$location.path("/teaser")
$scope.v.teaser = true
}
$scope.$apply()
})
$scope.goHome = function(){
$scope.$broadcast("goHome")
}
});
app.directive("ngMobileClick", [function () {
return function (scope, clickElement, attrs) {
clickElement.bind("touchstart click", function (e) {
e.preventDefault();
e.stopPropagation();
scope.$apply(attrs["ngMobileClick"]);
});
}
}])
HTML
<body ng-controller="mainCtrl as main" ng-mobile-click="goHome()" ng-class="{inverted: v.inverted, bg: v.offwhite}" space>
<div class="content" ng-view ng-hide="v.display"></div>
//My body code
<script ng-init="sw = 'some website'; id="about.html" type="text/ng-template">
<div class="about">
<p class="text" ng-click="next(); $event.stopPropagation()">
<p>some text</p>
<br>
<a ng-href="{{mail}}" ng-click="$event.stopPropagation()">some address</a>
</p>
</div>
</script>
</body>
The code for the about page is written into a script and it has hyperlinks (ng-href). Now my issue: As you can see, I changed my ng-click to ng-mobile-click for the body-section. If I also change it in the script for the hyperlinks, something weird is happening which I can’t really figure out (links change to hover color, but still no redirection to the ng-href.
For the desktop version, the click is triggering ngRoute, but I can also click the links. For the mobile version this is not possible any more. Any ideas how I can fix this? I know, there is no hovering possible, but somehow I need to detect the hyperlinks also on mobile devices without being redirected to the main-page.
As I said: this is my first try with Angularjs and I haven’t done any code for a while, please be as clear as possible!
There is another controller for teaser/about which I haven’t put here, as well as the directive for the keyup.
Any ideas or suggestions? Thank you so much in advance!

Rails 4 form_tag submitting to wrong controller action

This feels dumb, but so far everything I've read makes me feel like I'm doing it right but it's still not working.
I'm using a form_tag to submit params to a custom controller action. Instead of the action I indicate, it seems intents on submitting to the show action in my controller, which I need to reserve for profiles. Anyways here's the code (please excuse it's un-refactored state):
Doctors controller:
class DoctorsController < ApplicationController
def new
end
def show
#doctor_list = Doctor.find(params[:id])
end
def index
#doctor_list = Doctor.all
end
def search
end
def results
if params[:zip] && params[:zip].length === 5 && params[:zip]
#doctor_list = Doctor.where("zip = ?", params[:zip])
elsif params[:id]
begin
#doctor_list = []
#doctor_list<<Doctor.find(params[:id])
rescue
flash.now[:errors] = "That doctor does not exist!"
render 'search'
end
else
flash.now[:errors] = "That is not a valid zipcode!"
render 'search'
end
end
end
Routes:
resources :users
resources :doctors
root 'doctors#search'
get 'doctors/results' => 'doctors#results'
search.html.erb:
<% provide(:title, "Home") %>
<div class="hero">
<h1>Find an M.D.</h1>
<%= form_tag(doctors_results_path, method: "get") do %>
<%= label_tag("Zipcode: ") %>
<%= text_field_tag(:zip) %><br>
<%= submit_tag "FIND", class: "button"%>
<% end %>
</div>
Again, the issue is that I'm getting an error (Couldn't find Doctor with 'id'=results) because the form is using my show action vs. my results action. The application trace says the error is located at app/controllers/doctors_controller.rb:6:in 'show'. As an added confusion, I don't really understand why it's sending "id"=>"results" as part of the params hash on submit, but it seems like that might be a non-issue if it would use the correct controller action to begin with.
Thanks for any thoughts.
Yes its a priority issue. Since the resources :doctors is first, the GET show will be given the priority than get 'doctors/results' => 'doctors#results'
Moving the get 'doctors/results' => 'doctors#results' above resources :doctors should solve your problem
#routes.rb
root 'doctors#search'
get 'doctors/results' => 'doctors#results'
resources :users
resources :doctors