ReactJS Redux Loading Image Dynamically from Variable - reactjs

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:

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.

Disable emmett in functions for styled-components

I keep getting emmett autocomplete suggestions even inside the template string used with styled/css/createGloablStyle when using styled-components. Is there a way I can get around to disabling emmett inside the function template string or maybe at least push it down the suggestions? It's not a problem per see but I have been exploring vscode and want to know if there's a setting that helps.
Image attached below for reference. The body tag I want to disable in autocomplete suggestions.
PS: I don't want to disable emmett globally or even in the file, just in the function scope.

Changes to transitive dependencies not triggering live reload

I've added Snowpack 3 to my application and it works for JS/TS files as well as directly imported stylus files.
The file structure is similar to the following:
view.js:
import 'view-styles.styl'
export default function view() {
return (
<div className='example-view'>Hello World</div>
);
}
view-styles.styl
#require './colors.styl'
.example-view
background-color: $mainColor
colors.styl
$mainColor = #ff0000
The LiveReload/HMR works as expected when changing the directly imported stylus file. It does not work when changing anything in the colors.styl file. Changes in this file are only picked up once the view-styles.styl file is updated.
Is this a known limitation of Snowpack?
I would also be ok to trigger the update manually, as I have a way to identify these files using their filenames. I haven't found a way yet to trigger live reloads using Snowpack's JavaScript API. I was able to load the file using the SnowpackDevServer.loadUrl function, but that doesn't help either.
I was able to contribute this to the snowpack stylus plugin. The change was already integrated into the plugin: https://github.com/fansenze/snowpack-plugin-stylus

Require in reactjs is throwing cannot find module

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

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.

Resources