using links in react-i8next - reactjs

I was learning react through online sources, and I'm unable to find the solution for my problem-
suppose I have a json file -
"test":"This is a test file, contact at {{email}}"
and currently i use it as -
const [t] = useTranslation();
<div>t('test',{{email}})<div>
suppose I want to change the colour of the email text only, how do I do that?
I researched online, and read the Transcomponent documentation, but I'm unable to understand how to implement it.

You'll have to exclude the {{email}} placeholder from the translated text.
So this would be the i18n part:
{
"test": "This is a test file, contact at"
}
And this would be the React part:
const { t } = useTranslation();
return (
<div>
{t("test")} <span style={{color: "hotpink"}}>{email}</span>
</div>
);
There are a lot of variations for what you are trying to do (e.g. using external stylesheet, CSS classes, and so on), but this would be a straight-forward approach.

You can handle that using a css file, for that you need to import it to your react component file:
import './styles.css';
For this to work you should create a style.css file on the same folder/directory of your react file, after that you should set a css rule:
style.css
a {
color: hotpink;
}

Related

I want to write other languages code in react js

I am working on building a website.
I made all things, but now I'm stuck in adding code to the website.
I want to put some codes inside the JSX component but it is having some problems with adding { <<these types of symbols.
Is there any way I can write the C++ code or C code inside the react element?
import React from 'react'
const Template = () => {
return (
<div>
<h1></h1>
</div>
)
}
export default Template
The JSX won't appreciate the "{ <<", but if you want a quick in on this, you may try something like this -
const SomeCode = ()=><code>{`#include <stdio.h>;`}</code>
That might not be sufficient - you may need proper highlighting with specific programming language, formatting, etc. for what you might be building. But just for getting literals such as << working with JSX - you may take the above example as base.
In JSX, which is what react usees, brackets will be parsed.
Therefore, strings should be inside {`content`}, or you can define that code as a string, and place it inside jsx as below
const SomeComponent = ()=>{
const codeSnippet = `{ << whatever code blahblah`
return <div>
{codeSnippet}
</div>
}

how do I interpolate a Link component in Next-i18next / React i18next that changes position in the text

Currently I'm using Next.js with Next-i18next for I18N, but I understand that the React/i18next implementation is basically the same.
The problem I'm having is that I need to interpolate a next Link component inside some translation text, but depending on the language (English vs German), the order of the text and the link would change.
For instance the text I'm struggling with is: 'Accept data policy' vs 'Datenschutzerklärung akzeptieren'
As of the moment I have a quick fix by creating two values in the translation JSON files for the text and the link and then swapping the position based on the current language. Obviously this is not a sustainable solution. I have tried to utilise the 'Trans' component but this is showing some unexpected behaviour where the translation only kicks in after the page is refreshed, otherwise you see the text inside the Trans component.
example:
function LinkText({ href, children}) {
return <Link to={href || ''}>{children}</Link>;
}
return (
<Trans i18nKey="sentence">
text before link
<LinkText href="/data-policy">{t("dataPolicy")}</LinkText>
text after link
</Trans>
);
and the JSON in question:
{
"sentence": "agree to our <1><0/></1>",
"dataPolicy": "data policy"
}
Here's a link to CodeSandbox I made to replicate the problem with in React: link
(P.S The implementation of i18next doesn't seem to effectively swap out the languages in Codesandbox at the moment, but I included it as the code is there for a MWE)
Thanks in advance for your help, this has been driving me insane.
You had few missing parts,
Your i18next config was lack of a way to fetch the locale files, I've added i18next-http-backend.
You should use Trans component to inject the link to the sentence.
Your locale json should look like this:
{
"sentence": "Accept <0>data policy</0>"
}
// TranslatedLink.js
import React from 'react';
import { useTranslation, Trans } from 'react-i18next';
import { Link } from 'react-router-dom';
function LinkText({ href, children }) {
return <Link to={href || ''}>{children}</Link>;
}
export default function TranslatedLink() {
const { t } = useTranslation(['common']);
return (
<div style={{ padding: 50 }}>
<Trans i18nKey="sentence" t={t} components={[<LinkText href="/data-policy" />]} />
</div>
);
}
A working example: https://codesandbox.io/s/react-i18n-interpolation-issue-forked-ck8l4

How to Use SVG with React and ReasonML?

With create-react-app and JavaScript/TypeScript, I understand I'm able to "import" an SVG as noted below. How may I do so with ReasonML?
import { ReactComponent as Logo } from './logo.svg';
function App() {
return (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
}
Create React App uses webpack to transform SVG files into React components. If you’re using Reason with CRA, then all you need to do is provide a binding to the generated component. However, CRA will only transform the SVG into a component if the import statement is written exactly a certain way, which isn't how BuckleScript outputs import statements. (There's a GitHub issue about it here.) You have to import it with raw JavaScript and then bind to the imported value:
%bs.raw
{|import {ReactComponent as _Logo} from "./logo.svg"|};
module Logo = {
[#react.component] [#bs.val] external make: unit => React.element = "_Logo";
};
/* And we can use it like a regular component: */
[#react.component]
let make = () =>
<div>
<Logo />
</div>;
According to the CRA docs:
The imported SVG React Component accepts a title prop along with other props that a svg element accepts.
For any of the other props you want to use, you'll have to add them to your external binding.
If you're not using CRA, then you'll need to configure your bundler to do the same transformation. I'm not familiar with the internals of CRA, but this seems to be the relevant code from its webpack configuration.
We can use SVGR to handle the webpack loading and then import the module as we normally would.
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
module: {
rules: [
//...
{
test: /\.svg$/,
use: ['#svgr/webpack'],
},
],
},
//...
};
module Logo = {
#bs.module(`../../../../src/img/logo.svg`) #react.component
external make: {.} => React.element = "default"
}
...
<Logo /> // works
source: https://blog.logrocket.com/how-to-use-svgs-in-react/
I am the author of another solution that doesn't involve webpack.
It's a tool that can transform your svg files directly into .re files: https://github.com/MoOx/react-from-svg
This can create files for react (dom) or react-native(-web) (=> files generated use react-native-svg).
Feel free to try it :)
For example you can do (when the tool is installed from npm)
$ react-from-svg src/SVGs src/SVGs/components --with-native-for-reason --remove-fill
This will turns the files from svg/SVGs into React components into src/SVGs/components compatible for React Native with the Reason syntax.
The last option remove all svg fill props so you can use them as icons.
Note that the generated components accept width, height & fill props so you can adjust them when used.
Last bonus: since webpack is not involved, you can use this transformation only when you update your SVGs files & use this code directly with a Node runtime (JSX from Reason gets removed when converted to JS so the code can be consumed directly via Node without any transformation - which can be handy for tiny static sites/pages).

How to import bootsrap in just one component in react.js

Actually im "migrating" a website project where i used a template. There are some conflicts when i put the bootstrap link in the index.html. I would like to apply bootstrap just into one component to avoid this conflicts, but im not sure how to do it. Im pretty new with react.
The "conflicts" are just visual, like if importing bootstrap changes the rows and columns numbers
Unfortunately CSS is always global, so there's no easy way of doing this.
One way however, is to recompile Bootstrap and wrap it in a wrapper class.
Then, in your code, setup the wrapper class on a wrapper component and only classes that will be inside that wrapper component will be affected by Bootstrap classes.
Steps to do it :
(you'll need npm to do it)
download bootstrap sources here
unzip it, go in ./scss/bootstrap.scss
add a wrapper css class on all #import like so :
.local-bootstrap {
#import "function";
#import "variables";
/* ... */
#import "print";
}
go back to the root of the unzipped directory
run npm install and npm run css-compile
your local bootstrap is in ./dist/css/bootstrap.css, that's what you can add to your project
Then in your code :
<div class="local-bootstrap"> /* wrapper component */
/* inside, the code is affected by your local bootstrap */
<div class="alert alert-primary" role="alert"/>
</div>
/* outside it is not */
<div>
</div>
That said, it's pretty sure that the javascript part of bootstrap won't fully work because it relies on classes, this is a bit hacky, anyway.
If you're using SCSS, add the following to your SCSS file:
.local-bootstrap {
#import "~bootstrap/scss/bootstrap";
}
In your component file, make sure the SCSS file has been imported and then wrap the code you want to use bootstrap in a local-bootstrap classed div (see example).
Example:
import React from 'react';
import '<PATH TO SCSS FILE>';
const Example = () => {
return (
<div className='local-bootstrap'>
CODE YOU WANT TO USE BOOTSTRAP
</div>
);
};
You can use reactstrap, import what you need into your component file and leave the others alone.
Example:
import React from 'react';
import { Button } from 'reactstrap';
export default (props) => {
return (
<Button color="danger">Danger!</Button>
);
};
Using:
import 'bootstrap/dist/css/bootstrap.min.css';
You can import Bootstraps CSS into that specific component if you do not want it in your app.js or sitewide.

Is it possible to refer to css styles as objects in JS code?

I want to be able to do this:
import styles from 'switchstyle.css';
const Choice = function (props) {
const cssClasses = [];
if (props.active) {
// i think .active would be defined in the css file
cssClasses.push(style.active);
}
return (
<div
onClick={props.onClick}
className={cssClasses}
>
{props.label}
</div>
);
};
I saw something like that in a React book, but I cant get it to work -- I think I am missing some webpack plugin (I am guessing). THank you
This should work fine assuming you're using Webpack, except className can't take an array. A simple solution is to make it a string:
className={cssClasses.join(' ')}

Resources