Using nodejs & react together (in electron) - javascript

I have a React component which I use in my electron application.
// #flow
import React, { Component } from 'react';
import Home from '../components/Home';
import SentenceView from '../components/SentenceView';
import Dictionary from '../components/Dictionary';
export default class HomePage extends Component {
render() {
const aTestArray = [1,2,3,4];
return (
<div>
<SentenceView numbers={aTestArray} />
</div>
);
}
}
I am giving my SentenceView component aTestArray. Now, in reality I won't have this array available but will need to create it myself. Since React is only the View, I do not want to create the array with React, but outsource this to a function I have written in nodejs. It creates an array and then returns it. So what (as of now) I have written as
const sentenceArray = ['Hello', 'Mister'];
would ideally look something like this then:
const sentenceArray = createTheArrayFunction(); //returns array
However, I do not know how I can make this work. I do not know how to give my React component access to function which is in a nodejs file, or how else I would connect the two. I am using electron, so it should be possible for me to use nodejs (somewhere somehow). But I just have no clue how to put these things together. I would be glad if someone could help me out.

Related

How to evaluate a string as a React component?

I'm trying to make a website that lets users input some react code, then it renders it on the other side of the page, so they can see what it looks like.
My problem is, I have the user's source code as a string (which may return a function or class component), but I don't know how to convert that to an actual react component that can be rendered.
First I tried using the new Function() constructor, which lets you create a function from a string, which looks like this:
import {render} from "react-dom"
const userInputtedCode = `
return function App() {
return <div>Hello world</div>
}
`
const func = new Function("React", userInputtedCode);
const App = func(React)
render(<App/>, document.getElementById('WorkFlow'));
But this doesn't work, as I get the error SyntaxError: expected expression, got '<'
I have also tried libraries such as react-jsx-parser, but this doesn't fit what I need, as I want to make an entire react component which may contain state, props, nested components, etc, not just parse some JSX.
Any ideas of how I can convert strings of source code that return a function/class into actual react components? Thanks!
You can try this approach:
import React, { Component } from "react";
import { render } from "react-dom";
import * as babel from "babel-standalone";
const userInputtedCode = `
function App() {
return <div>Hello world</div>
}
`;
const babelCode = babel.transform(userInputtedCode, {
presets: ["react", "es2017"]
}).code;
const code = babelCode.replace('"use strict";', "").trim();
const func = new Function("React", `return ${code}`);
const App = func(React);
render(<App />, document.getElementById("root"));
PS: Make sure to run npm i babel-standalone before running the app.

How can I run user-input p5.js code in a React app?

I'm very familiar with p5.js, but brand new to web development. I've been getting familiar with React, and I'm working on building a React App that includes an in-browser p5 IDE. I am using Ace to build the code editor in a React Component without issue, but I'm not sure how to use that code to run a p5 sketch. This is my code so far:
import React from 'react';
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-chrome"
import "ace-builds/src-noconflict/ext-language_tools";
import "ace-builds/webpack-resolver";
import p5 from 'p5';
import './App.css';
let inputCode='';
function onChange(newValue) {
console.log(newValue);
inputCode = newValue;
}
export class Editor extends React.Component {
render() {
return (
<div className="container">
<div className="title-container">
<h1>p5 Code Editor</h1>
<button>Run</button>
</div>
<AceEditor
mode="javascript"
width="100%"
theme="chrome"
onChange={onChange}
name="UNIQUE_ID_OF_DIV"
editorProps={{ $blockScrolling: true }}
/>
</div>
);
}
}
export class Sketch extends React.Component {
render() {
return <div class="sketch-container" id="sketch-container"></div>
}
}
All I've managed to do at this point beyond rendering the code editor is store the input code into a string. I know there are methods to evaluate stringified code (eval(), new Function()), but working in p5 seems to make it more complicated. The only examples I can find of using p5 in situations like this looks something like:
const s = (sketch) => {
let x = 250;
let y = 250;
sketch.setup = () {
sketch.createCanvas(500, 500);
}
sketch.draw = () {
sketch.background(0);
sketch.rect(x, y, 100, 100);
}
}
let myp5 = new p5(s);
But if the user is coding in p5.js in the text editor, they shouldn't have to use the sketch.method() syntax whenever they want to use a function. So is there a way to translate input code written in p5.js into something readable in a React app? And if you can, how do you view the results within a specific div?
Instead of making the p5 code an actual React component, you could set up a designated file written in p5.js and write to it, and then run that code on a button press or whatever trigger you decide. Keep in mind that if you want to run it within a specific div you would need to add code to your setup function identifying that div.

Persist data between two pages with Next.js

I would like to refactor my Next.js webapp to have different pages handle different screens. Currently, I have this component holding several states to know in which screen I'm in. In the jsx section, I'm using {value && ... } to render the right component.
But I feel this is not good design, and won't be maintainable when adding more and more screens.
I would also like to avoid Redux as it is overkill for my project.
I was thinking about persisting data in cookies so I can retrieve them with getInitialProps in every component when rendering a new page, but is there a more elegant way?
I've read about tweaking the _app.js but I'm not sure to understand the consequences of doing so, and how it could help me..
Any suggestion?
When multiple of your pages need to make use of same data, you can make use of Context to store the result. It a good way to make a centralized storage without using complex and more self sufficient libraries like redux
You can implement context inside of _app.js file which must reside inside your root folder. This way next.js treats it as a root wrapper and you would just need to use 1 instance of Context
contexts/appContext
import React from 'react';
const AppContext = React.createContext();
export const AppProvider = AppContext.Provider;
export const AppConsumer = AppContext.Consumer;
export default AppContext;
_app.js
import React from 'react'
import App from 'next/app'
import AppProvider from '../contexts/appContext';
class MyApp extends App {
state={
data:[]
}
render() {
const { Component, pageProps } = this.props;
// You can implement logic in this component to fetch data and update state
return (
<div>
<AppProvider value={this.state.data}> // pass on value to context
<Component {...pageProps} />
</AppProvider>
</div>
)
}
}
export default MyApp
Now further each component can make use of context value by using AppConsumer or using useContext if you use hooks
Please read more about how to use Context here

Convert website from HTML,CSS,bootstrap & JQuery to React?

Hi guys hope you're fine, I'm student and I have this year to do some thing like a project to end my studies , so I chose to create a website (using React/Django) I already have the site but made by HTML,CSS,bootstrap & JQuery , so now i have to convert it to react , but i have a problem i don't know how to include some js files inside a components , every things else is going good, I need just what is in the js files to applied it in some components.
Hope you help me out.
cordially
You can have javascript code inside your components likewise
const Component = props => {
//javascript code
return (<div>-- Component JSX---</div>)
}
if the javascript code if just needed for the initializing of the component you can use react hooks to run a piece of code only one time after the component is created.
import React, { useEffect } from 'react';
const Component = props => {
useEffect(() => {
// javascript code
}, [])
return (<div>--Component JSX---</div>
}
the empty array as second argument indicates the useEffect hook that the effect should only be ran once after the component has been initialized.
So the way React works is you will be building "HTML" using React functional/class components like this example
import React from 'react';
//Just like a normal javascript function, it listens to in this
instance, the return statement. You're returning regular HTML.
function Navbar() {
return (
<div>This is some text built by react</div>
<p>Saying hello to react by building a functional component</p>
)
}
export default Navbar; //This right here is exporting the file so it can be
//used elsewhere just import it in other file.
So the return is where you will build your website, then in the next component you will import should look something like this.
Normally, it is called App.js or in some instances where it's more complex it's anythinng you want.
import Navbar from '../components/Navbar.js';
function App() {
return (
<Navbar /> //Now you don't have to write your main content in here you can
//just import it. Just like Navbar
<div>This is my main content in page</div>
)
}

import or require React components dynamically

I'm trying to import / require components dynamically, but somehow when I do it React complains. The require function does find it, but React throws an error saying it is missing some functions 't' etc.. All of this in an electron app.
I have a wizard setup (that is working, but not so elegant I think), where each page has it's own layout and jsx component. If I'd like to add a new page, I don't want to manage x-number of files, and at the moment I have to due to the setup I have currently. Below you can find what I want to achieve and what I'm doing now to achieve it. If there are any suggestions, code smells or better options please let me know as I'm quite new to React and ES2015 (as I'm from a C# background).
What I'm trying to achieve
export default class WizardPageContainer extends Component {
// Constructor
constructor(props) {
super(props);
}
// Render
render() {
const WizardPage = require(`./path/to/${this.props.step.id}`);
return (
<WizardPage step={this.props.step} />
);
}
}
How I'm currently doing it : which means I have to declare the imports / files first on top of the "WizardPageContainer" component.. Which means extra work and prone to errors/forgetting things. I should add, this code is working now ok, but I don't think this is elegant/future proof:
/* PAGES */
import WizardPage_Welcome from './pages/0.wizard.welcome';
import WizardPage_SystemCheck from './pages/1.wizard.systemCheck';
import WizardPage_SignIn from './pages/2.wizard.signIn';
import WizardPage_ExamCode from './pages/3.wizard.examCode';
import WizardPage_TakeExamination from './pages/4.wizard.takeExamination';
import WizardPage_Close from './pages/5.wizard.close';
const pages = [
WizardPage_Welcome,
WizardPage_SystemCheck,
WizardPage_SignIn,
WizardPage_ExamCode,
WizardPage_TakeExamination,
WizardPage_Close
];
/*/********************************************************************///
/* ******************************************************************** */
/* COMPONENT */
export default class WizardPageContainer extends Component {
// Constructor
constructor(props) {
super(props);
}
// Render
render() {
const WizardPage = pages[`${this.props.step.id}`];
return (
<WizardPage step={this.props.step} />
);
}
}
/*/********************************************************************///
I think it is about the "default". i have problem like this. Can you check this code;
https://github.com/robeio/robe-react-admin/blob/master/src/app/HasAuthorization.jsx#L10
Also you can check the example usage;
https://github.com/robeio/robe-react-admin/blob/master/src/app/HasAuthorization.jsx#L26
Your const pages needs to be an object, not an array.
You can see a working version I made of this here:
https://github.com/Frazer/meteor-react-nav/blob/master/lib/jsx/App.jsx
Best advice: Use Webpack to handle your imports, it's way more efficient than we could ever be.

Categories

Resources