Require in reactjs is throwing cannot find module - reactjs

Edit: Noob Helps here.
I checked a lot of similar questions already and none of them are quiet the same.
React is receiving an array of object from express. loop thru, get each object image link and add it to the source.
This is the original code
{this.state.currentTemplates.map((items, pos) => {
return (
<div className={`template `}>
<img src={require(`${items.link}1.jpg`)} />
<p>{items.name}</p>
<div className="buy">buy</div>
</div>
if image exist like this, require will find it and it will work.
but if i send a request to another function to check if image exist first, like a try catch.
<div className={`template `}>
//sending url to another function. Also I can put the function outside of class and just call without 'this' and it does not make any difference.
<img src={this.checkUrl(`${items.link}1.jpg`)} />
<p>{items.name}</p>
<div className="buy">buy</div>
Ex:
checkUrl(url) {
console.log(url); // receive right url '../products/templates/a.jpg'
try {
// try will require the right url but module cannot found it and it goes to catch. Now I can also put it in a variable var a= require(url) and it does not make a difference
require(url);
console.log("it works "); // it never gets to here.
return url; // this may not work once returned but it does not get to here.
}catch(e) {
//react jump to catch with "cannot find module '../products/templates/a.jpg'"
console.log(e);
}
}
I got Error: require cannot find module '../products/templates/1.jpg'
interesting thing. If i add the product folder inside the component folder with the templates.jsx file. it works.
Also it is not a syntax error, i may have made a typo replicating the issue here.
Recap: if I call require(url) straight from the src jsx, it found image.
If i pass url to another function to do a try catch. Console log the right url but require throw cannot find module.
is this a react limitation? is there a work around ? am i approaching this thee wrong way ?

You are approaching it in the wrong way, your images MUST be served, not requiring it as a module. It must be included in your static assets, or an external url served in other server. This is the common pattern, please don't complicate it.
If you have a public folder, just put it there like in the
public/images/image1.jpeg
Then in your code you can access it by:
<img src="/images/image1.jpeg" />
Provided you serve the assets.
Hope this helps!

look at first check the where the folder is line path to check the is the path that provides true or not the used this <img src={${items.link}1.jpg} /> without require
again if the image is external image found on web there will be no problem but if the is internal storage the check your correct path

Related

codeceptjs react testing - Clickable element was not found by text|CSS|XPath

I have a project made with react and rest api(php+mysql).I have to put it through a codeceptjs test.The app is working properly with countless of manual testing, and as far as I can see, the codeceptjs test is working too, but it gives the following error:
Error: Clickable element "ADD" was not found by text|CSS|XPath
at new ElementNotFound (node_modules/codeceptjs/lib/helper/errors/ElementNotFound.js:14:11)
at assertElementExists (node_modules/codeceptjs/lib/helper/WebDriver.js:2835:11)
at WebDriver.click (node_modules/codeceptjs/lib/helper/WebDriver.js:917:7)
at processTicksAndRejections (internal/process/task_queues.js:97:5)I }) => {
I.amOnPage('/');
I.click('ADD');
I.seeElement('#product_form');
I.fillField('#sku', 'SKUTest000');
I.fillField('#name', 'NameTest000');
I.fillField('#price', '25');
I.waitForElement('#productType');
I.selectOption('#productType','DVD');
I.waitForElement('#size');
I.fillField('#size','200');
I.click('Save');
My add element looks like this:
<Link title="ADD" to="/add-product">ADD</Link>
Can someone please help me out why is this error appearing and how can I solve it? Thanks in advance!
Update:
I did a couple more tests, and I noticed that sometimes it gives back less/different errors depending on the test's time. For example:
http://165.227.98.170/open?testName=ed
http://165.227.98.170/open?testName=ah
http://165.227.98.170/open?testName=bc
My guess is that is has to do with how react loads in the html elements and manages the rest api calls. How/what should I change in the app to accomodate the test script?
Seems like the problem was I put the whole home page's load after the rest api call by accident.

Is there an include parameter for sentry/browser to include only specific files?

I want to add sentry to my React widget. it's a Hotel Reservation widget and lots of hotels use it.I added #senty/browser to the project and now there is a problem whenever any error happens in their websites i receive an issue from sentry. but i don't want to get errors from their codes.
here's my simple Sentry config code:
import * as Sentry from '#sentry/browser'
Sentry.init({
dsn: SENTRY_DSN
})
I want a way to tell sentry only send errors from the widget scope ( only from some js files that belongs to the widget). Any help would be appreciated.
I searched and all i found was "beforeSend" function that will be called before sending the issue. but i couldn't figure it out. the data argument of beforeSend does not contain any usefull data for checking whether the error is from my code or not. and I don't know if it's possible to prevent sending issue inside beforeSend.
PS: the way that these hotels add the widget to their website is simple. they just have to add a script tag to the footer of their website (the built main.js of my project) and a div tag in wherever they want the widget to be placed (this div tag must have a specific ID).
Try use this one:
import * as Sentry from '#sentry/browser';
init({
beforeSend(event, hint) {
const error = hint.originalException;
if (error && error.message && error.message.match(/database unavailable/i)) {
event.fingerprint = ['database-unavailable'];
}
return event;
}
});
Gihtub issue

ReactJS Redux Loading Image Dynamically from Variable

I am currently working on a React + Redux Project and wanted to use language messages to render an image.
The problem is that, because the image name is dynamic (because of the language switching), I can't use require(imageVar) to load the image.
What I currently am working with is this (this is inside of the render() function):
FormattedMessage {...messages.fullLogo}>
{
(fullLogo) => <Img src={require(`${fullLogo}`)} alt="Banner" />
}
</FormattedMessage>
This should theoretically load the image from the url (yes fullLogo is a full url to the image).
What I tried inside of src={} was:
require(`${fullLogo}`)
require(fullLogo)
require("" + fullLogo)
require(String(fullLogo))
require(fullLogo.toString())
Everytime I try one of these (except the 3rd one - gives me an fatal error) I get an "Could not Load Module './img/image.png'" error.
I guess this means, that the name does load but require somehow cannot access the variable.
However if i put the path directly into the require() function. It successfully loads the image.
I don't want this though. I want it to load it dynamically.
Maybe you guys have some experience with it.
Thanks in advance!
PS: If you need any extra code, let me know!
You can't dynamically require files by variable at runtime, since require happens before runtime, when you bundle your app together (e.g. using webpack).
Based on how the packager works, this isn't really possible with require.
Packaging happens once before runtime so those variables don't have values yet.
What do you mean by langage switching ? What does message.fullLogo contains ? If it contains an url, just use that url without require:

How to use Yandex.Metrika in Meteor+React app?

I have a Meteor app, all UI components are built with React. I use FlowRouter for routing.
Now I want to add analytics with Yandex.Metrika service.
I found this package for React: https://github.com/narkq/react-yandex-metrika
But I how I have to use it? For what reason do I need <YM /> component from this example?
import {Initializer as YM} from 'react-yandex-metrika';
// Use the initializer to add the script to your page somewhere.
var MyComponent = React.createClass({
render: function() {
return (
<div>
// SNIP
<YM />
// SNIP
</div>
);
}
});
And where should I initialize the tracker object? I read this:
// This is supposed to be executed only in browser and only once.
// Because of that, the most sensible place for this code is right after you javascript bundle.
ym.init([987654321]);
But what is javascript bundle and where should I place my im.init(id) code?
Actually all what I need is to have funsctions to send data to Metrika, such as hit (pageview analog rom ga), reachGoal and so on.
thank you for your answers!
For what reason do I need component from this example?
You need it to load metrika's main code
How metrika works:
webmaster (you) inserts small piece of js code (loader) to all pages. this code append async script with main code (it's a bit bigger than loader) and create instance of metrika object ('counter') - new Ya.Metrika(...params). Instance will be available in global variable named yaCounterXXXXX, where XXXXX is your counter's id.
So, <YM /> component is loader from previous paragraph.
Actually all what I need is to have funsctions to send data to
Metrika, such as hit (pageview analog rom ga), reachGoal and so on.
There is doc about that at the bottom of readme. But I don't see filter by counter id for that methods. Maybe I make a pr to add this functionality. In any case you can use global variable yaCounterXXXXX like this yaCounterXXXXX.hit(url, params) or yaCounterXXXXX.reachGoal(goalId, params)
I hope I helped you.

Using $javascript helper issue in CakePHP: "Undefined variable: javascript"

I have problem when I want to use $javascript->link('prototype') in the default.ctp layout. It returns:
Undefined variable: javascript [APP\views\layouts\default.ctp, line 6]
I also added this code into app_controller.php:
<?
class AppController extends Controller {
var $Helpers = array('Html','Javascript','Ajax','Form');
}
?>
The file prototype.js is already in webroot/js folder.
Where is the problem?
I have had this problem many times. It's usually either caused by the controller code being overwritten somewhere or some weirdness happening with Cake's automagic stuff. If you remove all of your helpers and then add them one by one it will probably work eventually.
Another perfectly valid way of generating JavaScript links is by using the following which doesn't access the $javascript variable:
echo $html->script(array('prototype'));
It has to be $helpers instead of $Helpers.
You just open the error console of the Firefox browser (shortcut key ctrl+shift+j).
Find the error and click on it.
After clicking, you will see the head portion.
Note the location of the JavaScript file (*.js) which you want to locate (you will see the location is not correct).
Cut the JavaScript file from webroot and paste it in given location of head block.
Example:
This will show on error console. Map_demo is my project, and in its place your project name will display:
<script type="text/javascript" src="/map_demo/js/test.js"></script>
Cut the JavaScript file from webroot
Make the JavaScript folder in your project application folder, /map_demo/js
Paste test.js (your script file) here
Now your JavaScript function will work.
Just in case somebody else comes across this bug/issue: it was also happening to me, until I commented out the line $session->flash(); in my default layout. Realising that the error was being caused by flash messages, I went back to the controller and noticed that I was using separate layouts for flash messages (e.g. 'message_alert') and that those layouts didn't actually exist in the view folder!
So remember, errors like this could mean that a file is not defined yet. Best of luck.

Resources