JSX without react. Just pure es6 and HTML - javascript

Good day fellow devs! Is it possible to return a jsx format from a function without using react? My project is just pure Es6 and HTML. Here's what I want to do, I want to create a separate files for functions and HTML then call the HTML format files in the functions.
For example, here's my main.js:
import renderHTML from './display/render.js';
import createElement from './functions/createElement.js';
var popup = document.getElementById('popup-container');
const HTML = `${renderHTML}`;
const Fragment = createElement(HTML);
popup.appendChild(Fragment);
Then in my renderHTML file where it's jsx format, here's the content:
export default function renderHTML() {
return (
<h1>I am the content! Rendered successfully!</h1>
)
}
There, hope that made sense lol.. But yeah, the output of that is either its code or object. Any help or advice if I'm doing it wrong is much appreciated. Thank you so much and have a nice day ahead!

Related

Best way to include custom react components between strings/p-tags?

tldr: New to frontend. Trying to include custom components within p-tags for a website, I've tried various methods but can't seem to get it to work unless I hard code the content into the return bit in my react component - this isn't viable as I would like to have many p-tags which would change on my website when a user presses next.
Hi everyone! I'm new to front end programming, and this is my very first question, so please excuse any incorrect terminology and/or question formatting!
I'm currently working on a react project where I have created custom components to include in my webpage. These components work when placed between p-tags.
For example, I made a custom component and it works as expected when I do something like:
function test{
return(
<p>Hello! This is a <ShowDefinition word="website"/> which I made using react! </p>
)}
However, I intend to have lots of content which would change using an incremental index, so I've placed my content in a separate jsx file to store as a dictionary.
I found that when doing something like this:
function test{
return(
<div>{script[index].content}</div>
)};
where
script[index].content = '<p>Hello! This is a <ShowDefinition word="website"/> which I made using react! </p>';
it just shows up as a string literal on the webpage. I've tried to wrap my string in {} but this did not seem to work.
I've also tried dangerouslySetInnerHTML with a dompurification to sanitise the html code
dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(script[index].content)}};
This worked however it excluded all of my custom components. So for the example sentence it would show up on the page as "Hello! This is a which I made using react!"
I understand now this doesn't work because dangerouslySetInnerHTML cannot convert custom components/only accepts html, however I am now at a complete lost as to what to do.
I have thought of storing the content in a md file then parsing it however I have little knowledge of md files/md parsers and from what I've found I don't think solves my problem?
Any advice would be greatly appreciated.
Thank you so much.
Ok, so first of all, this is definitely not how you should think when playing with React. Even if this is technically possible with things like React.createElement or dangerouslySetInnerHTML, I suggest you look at this first. I will help you get the thinking in react.
However if I had to do this in React, I would probably use a custom hooks or any conditional logic to render my jsx.
codesandbox
import "./styles.css";
import React from "react";
const useContentFromIndex = (index) => {
return () => {
if (index === 0) return <p> Index 0 </p>;
if (index === 1) return <p> Index 1 </p>;
return <p> Index 2 </p>;
};
};
export default function App({ index = 0 }) {
const CustomContent = useContentFromIndex(index);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<CustomContent />
</div>
);
}

Confusion with default import of React

To import React we write import React from 'react'.
But this is a default export right ? So if I change its name to something else other than React it should also work. But it doesn't work. Can anyone please explain why?
Essentially, JSX compilers (like Babel/TypeScript) convert the JSX code to pure JavaScript.
For example, the following JSX code:
const Element = () => (
<div>
Hey there
</div>
);
is compiled into:
const Element = () => (
React.createElement("div", null, "Hey there")
);
Which is now valid JavaScript that can be parsed by the browser.
As you may have noticed, it uses the React.createElement function to create the div. This is why changing the name of the import doesn't work - the compiler still tries to use React.
Babel lets you configure this using the pragma option, if desired, allowing you to use a different function name.
TypeScript can do the same using the jsxFactory compiler option.
It works so, as you use Babel, or something similar, to translate JSX.
So when you input something like this:
function AComponent() {
return <div>Hello world</div>
}
You will get the next transpiled code:
"use strict";
function AComponent() {
return React.createElement("div", null, "Hello world");
}
By this reason you should use the definite name of React.
You can try it here: https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=AQ4MwVwOwYwFwJYHsrAIIGEkFsAOKBTKOACgEpgBvAKFBACcC4J7UAeAEwQDcA-ACQIAbIUmAB3JPSEc2Aei59aoAL5A&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.4&externalPlugins=

Where should I put a 3rd js function and how to use it in .vue file?

In my vue app, I used a 3rd single js file contains a function, say getXXX looks like
(function(){function e(b,e,f)......&(window.getXXX=e)})();
I use this getXXX in my A.vue, if I just put this function inside A.vue, it works fine.
Now I'm thinking to put this long function to a single file, Where should I put a 3rd js function and how to use it in .vue file?
You can write a function in the another single js file. And export that function like this,
single-js-file.js which contains your function
export const getXXX = () => {
console.log('that works!');
}
And you can import it in the A.vue file like this,
import {getXXX} from './path-to-that-single-js-file'
And you can call that function in any of the life cycle hook in Vue
created() {
getXXX();
},
I would rather create a plugin for that (https://v2.vuejs.org/v2/guide/plugins.html), to be more specific about my approach, you can import this javascript file in your html entry point, this will expose the API of this library to the windows object in the client, while you can use window.xxx is not a clean solution, so you can create a wrapper in the form of a plugin and just return the instance of this library as a global object.
Hope this helps,
Cheers.

How to combine emojione with markdown in React?

Right now I am trying to parse some text with both react-emojify and react-markdown. I would like to combine somehow the functionality of both utilities.
Problem is (if I understand correctly) that both convert string into React DOM. When I run emojify on content the result cannot be passed into <ReactMarkdown source={result} /> and vice versa.
I was thinking about doing sth like serializing React DOM into HTML and allowing some tags in the other parser, but both have rather limited options when it comes to making them compatible (e.g. emojify spits emoticons as spans which cannot be allowed in ReactMarkdown).
Have anyone else tried that? Is there some way (even by changing libraries) that could help me achieve this?
I managed to make things work by replacing react-emojify with emojione:
import emojione from 'emojione';
import React from 'react';
import ReactMarkdown from 'react-markdown';
class ExampleComponent extends React.Component {
render() {
const content = this.props.content;
const emojified = emojione.shortnameToImage(content);
return (
<ReactMarkdown source={emojified} />
);
}
}
Later on I only had to tweak how emojis are shown by changing .emojione class properties in CSS (as opposed to passing option object into react-emojify function).

Re-transpile JSX on the fly in a reactjs app

Is it possible to access and modify the JSX used to create a React class and re-transpile it on the fly. For example, if you had the following:
var Item = React.createClass({
render: function () {
return <div>Hello</div>
}
}
How could we: access the raw JSX, modify it to return something else, then transpile so the changes could be seen?
YES I understand this could be extremely dangerous.
It's probably easier to compile the JSX to JS first, and then use something like esprima to make the changes you need on the AST esprima gives you. Then pretty print it to JS again.
But I have to ask what your use case is, because it doesn't seem like the very best of ideas.

Categories

Resources