Interpolation with <Link> of react-router - reactjs

I'm working with react-router, and actually what I want is very simple, so I won't be too long, is just to get a string with a <Link> of react-router interpolated like:
const link = (
<Link to={"/terms"}>{"terms"}</Link>
);
const label = (
`something ${link}`
);
Actual result:
something [object Object]
Expected result:
something terms
Anybody knows how do I get the expected result?

I ran into the same issue and couldn't find a way to evaluate the Link object toString, within an interpolation; however, I found a workaround as (based on your setup) you can pass in multiple nodes in JSX as props. As an example, you could do something like:
label={
<div>
<span>something</span>
<Link to={'/terms'}>terms of use</Link>
<span> and other terms and such</span>
</div>
}
The link could then evaluate to the string/html output you are looking to render. Hope this helps !

You can take a look at: https://www.npmjs.com/package/jsx-to-html
Otherwise, you can use jsx-transform package which will give you information regarding the props you are passing.
const linkString = jsx.fromString(link, { factory: 'mercury.h' });
console.log(linkString); // 'Link({to: "/terms"}, ["terms"])'
Then you can use regex:
const linkPath = eval(linkString.match(/{(.*?)}/)[0]); // '/terms'
const label = `Whatever`;

Related

How to render dom element based on value of passed prop?

I am working on a Text component that has a prop as, this can be any valid text dom element i.e. <Text as="p" /> or <Text as="h1" />. Within component itself I want to render respective dom element and thus far I ended up with a big switch statement for this, however I am wondering if there is a better approach that is less verbose?
I tried looking at ui libs like chakra and material ui that have same patter, but quiet frankly wasn't able to figure it out form there.
I would then have an object store it somewhere outside of your component like in constants called e.g htmlOptionTag there you can have every expected props "as" :
const htmlOptionTag = {
"a": ({label, ...rest}) => <a {...rest}>{label}</a>,
"div": ({text, ...rest}) => <div {...rest}>{text}</div>,
.....
};
Then import and use it inside Text component :
return htmlOptionTag[as](props) || null;
I created a function domElement and it accepts two parameters :
tag and their attributes.
/**
* #param {*} tag "a"
* #param {*} attr {"href":"https://example.com", "class":"custom-class"}
* #returns
*/
const domElement = (tag, attr)=>{
let ele = document.createElement(tag);
if(Object.keys(attr).length > 0){
for(let i in attr){
ele.setAttribute(i,attr[i]);
}
}
return ele;
}
Now if you run domElement("a", {"href":"https://example.com", "class":"custom-class"})
It will return :
Note : You can also pass function as {"onclick" : ()=>{console.log("I am a function")}}
You can also tweak my answer to ReactJS specific. I don't have much time right now, so I just gave you a hint on how you can minimize your code without having ifelse or switch statements.
After playing with this I discovered that react has React.createElement function that takes in dom element strings like a or h1 for example, so to achieve my goals all I had to do was
return React.createElement('a', otherProps)

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>
}

Passing array as props in React Native

I have been reading a lot of threads and I couldn't find a solution to my problem.
I am passing some arguments to another React Native component in the following way:
<Footer buttonsActive={{ firstButton: 'true', secondButton: 'false' }} />
When I console log the parameter in Footer I get:
Object {
"buttonsActive": Object {
"firstButton": "true",
"secondButton": "false",
},
}
It looks fine, but when I try to console log the elements in the following way:
console.log(buttonsActive.firstButton);
I get an undefined error. What is the way to access these 2 values without iterating by using .map() and asking if (var == firstButton)....
Thanks
It may be the buttonsActive object that is not found is your context. It should be a prop inside your Footer.
Maybe try with console.log(this.props.buttonsActive.firstButton); inside the Footer.
I finally understood how it works, so one can send the parameters in this way:
<Footer firstButton secondButton={false} />
And one accesses them in the Footer component in this way:
const Footer = (buttonStatus) => {
const firstButtonColor = (buttonStatus.firstButton ? 'black' : 'grey');
const SecondButtonColor = (buttonStatus.secondButton ? 'black' : 'grey');
I hope it helps.

How to render a template string as HTML?

Let's say I have a simple template string :
const foo = `<div>foo</div>`;
How do I go about rendering this template string as HTML ?
It renders it as plain text if I do the following :
return({ foo });
Output:
<div>foo</div>
Expected output:
foo
I think what you try to do is
const foo = `<div>foo</div>`;
<div dangerouslySetInnerHTML={{ __html: foo }}></div>
Related question.
React documentation.
You note reactjs as a tag here. Instead of specifying the html as a string, make foo a functional react component.
To do that, make sure you have import React as 'react';.
Then, set foo as the functional component, i.e.:
const foo = () => <div>foo</div>;
Then, you can use that wherever you please. React components are just functions (or classes) that return jsx.
Your question is fairly open-ended, so you may be looking for some of the above answers, but this is one approach.
Off the top of my head there's 2 ways to parse a string (doesn't have to be a tl) into HTML: .innerHTML property and the more powerful .insertAdjacentHTML() method.
Demo
var tl = `
<video src='http://media6000.dropshots.com/photos/1381926/20170326/005611.mp4' controls width='320'></video>`;
document.body.innerHTML = tl;
document.body.insertAdjacentHTML('afterbegin', tl);
if you want to show the string of html as html page its better to do this:
<text>{{ info | safe }}</text>

How to render a HTML string in React?

I have a string like < b >hi< /b >. I have to render it as "hi". Can someone let me know an equivalent thing like innerHTML in Angular that I can use in React?
you can try dangerouslySetInnerHTML with the enclosing tag:
<div dangerouslySetInnerHTML={{ __html: yourhtml }} />
According to official React docs
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
To avoid the potential security vulnerabilities (such as XSS attacks) that are present when using dangerouslySetInnerHTML, you can do the following:
First use DOMPurify to clean the HTML.
import DOMPurify from 'dompurify';
let clean = DOMPurify.sanitize(dirtyHtmlString, {USE_PROFILES: {html: true}});
Then it can be rendered using react-render-html as Salman Lone said:
import renderHTML from 'react-render-html';
<div>
{renderHTML(clean)}
</div>
in my case, I used following pacakge.
react-render-html
According to the website "https://reactjs.org/docs/dom-elements.html" you should use dangerouslySetInnerHTML in order to avoid cross-site scripting (XSS) attacks. However, if you are controlling the string that you want to render then that may not be necessary. If you wish to render HTML this way then as the above website explains, you may do so in this way:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
I personally do not like the dangerouslySetInnerHTML method (mostly because it has the word dangerous and that scares me). I cannot say if the next method is better, safer, faster etc but I like it much more. The second method that you can use is to render the HTML with useRef.
An example of this method is:
import React, {useRef, useEffect} from 'react'
export default function Example() {
const aRef = useRef()
const content = '<p style="color:red">hello</p><h1>world</h1>'
useEffect(()=>{
if(aRef==null)return
aRef.current.innerHTML = content
},[aRef, content])
return <div ref={aRef}/>
}
I forgot to do testing for setting class, id, ref, values etc via string.
If someone wants to add to this answer, please add examples for every React operation like I have done with style.

Resources