I try to use t function of i18next outside of React Native component. In some places I need to use "t" in function which is defined not in component. I don't know what would be the best way to pass the "t" into such functions.
Currently I'm thinking of these options:
import "t" from i18n config file on top of the file where I want to use "t"
use hook useTranslation() from 'react-18next' (not sure if this works if we use the hook not in component)
also I can pass "t" as argument to the function , but this could be overcomplicating the function.
What option do you think is the simplest and the best?
So far I use useTranslation hook and sometimes importing "t" from i18n.js config file, but I need to stick to one method of importing "t".
I personally use the first option which works pretty well and don't add complexity to function's parameters
I personally do this inside utils files which do not contains any component:
import { t } from 'i18next';
export async function generateMailBody(user, isContact) {
const yourMessage = isContact ? t('Your_message') : t('Problem_description');
...
}
Related
I'm using functional components and exported a function and imported this function in my App.js.
How do i use that component, for some reason editor doesnot take the component.
I'm also using scss, anyone please check if the process of adding scss is correct or not!!
In react to import & exporting a file there is a naming convention.
You should perform these changes to your App.js and skeletion_loader.jsx file.
In skeleton_loader change the function name from this skeletonLoader to SkeletonLoader and in the App.js file import it as import {SkeletonLoader} from "../xyz.jsx";
Sorry for the noob question in advance. I have got a button, and I have a function in a different folder which I am trying to execute... I have tried to import the function from my other folder however it does not seem to be exceuting...How do I call this correctly?
ModalTopBar.js
import LineageContent from '../../ReusableComponents/Lineage/LineageContent'
<Button text='Get SQL' onClick={LineageContent.onHandle} />
LineageContent:
const onHandle = () => {
console.log('clicked')
}
File path to where I am importing lineage content if it helps:
First of all lets clear that the Components in reactjs is reusable so you can't simply import a new instance then use a nested function from this component
if the Component that you want to use a nested function is parent or even ancestor to the current component then you should props and pass the function address throw it
else you should use something like redux and save this function address in a store then use wherever you want this is a bad practice to use redux
I would like to store some variables inside a module (export) to be used as constants though out my react app. I would like to avoid context because there is no need for components to re-render and also I need those constants to be used outside my react components.
Where should I do it (where to import it), in order to prevent garbage collection?
One idea I have is to import and re-export it on top of my root component.
EDIT:
To be more precise, there will be a component that will set the constant once (mutate the variable), so that other components or files can access it.
So, what you will need is some sort of setter/getter pattern. Though I mostly don't recommend it unless you know what you are doing, because React won't re-render if the variable changes and because of that you need to be sure the variable is set before it is used.
You should have something like the example below in order for it to work the way you want. You can find an example of it working on this Codesandbox.
export let MY_VARIABLE = "";
export const setMyVariable = value => (MY_VARIABLE = value);
PS: I've added some console.log to the code in order for you to see how the import/get/set behaves.
After digging more into this I found that es6 module spec states:
When import your module it gets loaded => parsed => evaluated and cached (singleton). It also says that when you import modules its value is passed by reference (aka assignment). I didn't find anything mentioning when or how es6 modules are unloaded from that cache.
So that means, when you import a module once, it is there for as long as the program is running, and all modules access its values directly.
reference
https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/
https://medium.com/#mivanichok/understanding-es6-modules-in-depth-article-b49612926e39
You can create an config.js inside src folder and write the your constant variable like
//config.js
module.exports = {
CONST_VAR : 'const value',
}
import config.js in your component and use it
I have a setting style file like:
GlobalStyles.js
export const GlobalStyles={
ViewContainer:{flex:1, justifyContent:'center', alignItems:'center'},
Center:{justifyContent:'center', alignItems:'center'},
FontNormal:15,
FontMedium:18,
FontLarge:28,
FontHeader:38
}
module.export={GlobalStyles}
and when i used it in another JS file, let say Home.js. i want to vscode know every Key:Value i've defined,
with those export in GlobalStyles.js vscode suggesting an import style like this:
import { GlobalStyles } from '../Component/GlobalStyles';
and my expected result is something like:
import { ViewContainer, Center, FontMedium, [and so on]} from '../Component/GlobalStyles';
how to let vscode suggesting me Auto Import foo from path/to/GlobalStyles when i'm typing foo? where foo is like ViewContainer, Center, FontMedium, [and so on].
The feature you're talking about is called Auto Imports. To answer your question, this feature exists and works by default in VSCode.
Here is a sample of how i've used it in a React project. Here I have a component inside a folder with the same name. Outside of that folder is a file I called ModuleExports.js and it currently has the following code.
import Navbar from "./Navbar/Navbar";
export { Navbar };
For reference, export is an alias of module.export so feel free to use them interchangeably. This is a component so when I try to use it as such you can see from the screenshot I am suggested an import to use.
The same can be done without being a component. I'll declare a testObject inside the same file ModuleExports.js and export it.
Then let's see if intellisense will pick it up.
There it is. I hope this helps and do ask if you want more clarification or are running into issues.
In this case, the mistake seems to be using dynamic export. That's old CommonJs style. VSCode uses typescript tools for static analysis. To take advantage of that, you have to use ES6 export.
CommonJs: module.export={GlobalStyles}
ES6-modules: export GlobalStyles
The significant difference between two is that CommonJs variant is simply variable which is defined at runtime. Ie. there is no way to know what you are exporting without executing the code. ES6 export is reserved word. It's construct which cant be changed after definition which also means, it's type definition can be found without actually executing the code.
Typescript, Babel etc provide interoperability between two module systems but they are two very different things by spec.
If you have a parent component file that already imports React, why does any of its rendered children files also need to import React? Is it just a safety measure in case those children are ever rendered somewhere else where React has not been imported yet?
In nodejs each file is a module, that has its own scope of variables. When you import variable into file (React for example) you add this variable to the module scope, but not to the global scope.
In case of webpack you can use providePlugin to easily make React variable global:
new webpack.ProvidePlugin({
React: 'react' // ReactJS module name in node_modules folder
})
After that you are able to skip importing React variable in all of your modules. Webpack will do it itself where needed.
If you use JSX and babel, you have to import React in every file because babel-preset-react will transpile your JSX code into React.createElement() calls, so this code
const Foo = () => <h1>Test</h1>;
will be
var Foo = function Foo() {
return React.createElement(
"h1",
null,
"Test"
);
};
DEMO: Babel REPL
This is the reason why React should be accessible in the proper scope and one way to do it, is to import React in a file.
The root of the question is one of dependency management -- how do I, the author, describe and obtain external dependencies I need in my "thing" (application/component/module) for it to do its job?
JavaScript benefits (or suffers) from having a global namespace in which dependencies can be injected. While this can often simplify dependency management in the short term (e.g. you can ignore it and expect everything you need to be available in the global namespace), it can often cause issues as an application grows and changes. For example, given an application with multiple contributors, one might decide to change a part of the application to no longer use a particular dependency and therefore remove it. If another part of the application needed it but that dependency wasn't formally declared anywhere, it could be easily missed.
To do dependency management well, each discrete "thing" should describe its dependencies independent of any other "thing" such that it can be safely used in any given context. This ensures that each "thing" has exactly what it needs no matter how it is used and what its "parent" (the code importing the "thing") has.
An alternative to this approach is dependency injection. In this model, the "thing" provides an interface for passing the dependencies into the "thing" from the consumer. There are flexibility and testability advantages to this which are out of scope of your question. :)
// export a function that expects the React and PropTypes
// dependencies to be injected as parameters and returns
// the component rather than importing the dependencies
// and exporting the component
export default (React, PropTypes) => {
return class extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired
}
render () {
return (
<div />
);
}
};
};
All of that to say, it is somewhat a "safety measure" to have each "thing" import its own dependencies. It lets you safely refactor your code without the cognitive overhead of remembering what is providing those dependencies.
The reason is to avoid unnecessary compiled a JavaScript code that you don't have to compile jsx. For example, you have a file that have a function to do adding, or whatever function that doesn't need to compile jsx, then you don't put import React from 'react' on the top of that file. This will save you compile time.