Call react component from javascript - javascript

so i have that big project and everything is on pure javascript like Class.create...prototype and functions that render every component on that page and in render with react.I mean when i type function.createElement("div") somehow it create react div.. and so on and everything is on PURE javascript .. so my question is how can i create file with normal react components and and call that react component from that js file? Thank you

From what I understand from your question is that you need to reuse the react component. For that you need to do two things
Export you react component.You can do it as
module.exports = App;
if your react component is like var App = React.createClass()
Secondly in your other react component where you want to reuse this component you can import it as
import {App} from './path/to/resuable/component';
Now use this component in the render() {} function as <App/>

Related

What is the difference between react: class vs function App()?

When I download a react project, my default in App.js is :
function App()
However, a lot of YouTube tutorials uses:
class App extends React.Component {
Is there a difference between the two? Is one just older?
Functional components have somewhat replaced class components because they generate less output code.
Previously, classes were used to be able to use the state. However, this is now possible with the useState hook.

How to add/use React component in only one part (cart page) of my existing node project?

Up until now I have been using create-react-app to build React applications and components.
However, I have a project that I'm working on which was built in node using pure JS for Dom manipulation and I wanted to add react to one page only (the cart page).
All tutorials I had watched assume you are starting project from scratch and I can't seem to figure out how to add React to just a single part of my project.
Can someone point me in the right direction?
I would recommend you start here:
https://reactjs.org/docs/rendering-elements.html
The React Docs actually also point at this tutorial for a non 'create-react-app' tutorial: https://blog.usejournal.com/creating-a-react-app-from-scratch-f3c693b84658
This is the React Docs for rendering elements. The TLDR version:
In your HTML file, where you want your React component to go, create an empty div and give it a unique name (i.e. 'app' or 'react-component')
Then create your component, etc. and have ReactDOM render on the unique id name.
To get it to render, in your node app, point it at the build path, typically bundle.js
I have got this working and managed to use React components (written in JSX) for specific parts of my custom JavaScript app (bundled via Webpack). You basically need three things.
1) Your custom JavaScript app
// MyApp.js
import { renderMyReactComponent } from "./MyReactComponent.jsx";
class MyApp {
// Call this when you want to show your React component
showMyReactComponent() {
// Create an empty div and append it to the DOM
const domElem = document.createElement("div");
domElem.classList.add("my-react-component");
document.append(domElem);
// Render your React component into the div
renderMyReactComponent(domElem);
}
}
2.) Your React component
// MyReactComponent.jsx
import React from "react";
import ReactDOM from "react-dom";
class MyReactComponent extends React.Component {
render() {
// JSX, woah!
return <h2>My React Component</h2>
}
}
// A way to render your React component into a specific DOM element
export const renderMyReactComponent = (domElem) => {
// NB: This syntax works for React 16.
// React 18 requires a slightly different syntax.
ReactDOM.render(
<MyReactComponent />,
domElem
);
}
3.) A way to parse jsx files and build the app
I use Webpack and amended my existing Webpack configuration based on this article: https://medium.com/#JedaiSaboteur/creating-a-react-app-from-scratch-f3c693b84658 (The official React documentation also points at this tutorial)
Useful Articles
A good read is this article from the official React documentation: https://reactjs.org/docs/add-react-to-a-website.html. This also explains a different way to integrate a React component into your existing JavaScript app using script tags instead of Webpack.
You might also be interested in this answer to a similar question as yours.
As #pinkwaffles pointed out in their answer, the following article helps to understand rendering a React component into a DOM element: https://reactjs.org/docs/rendering-elements.html
PS: Note that at the time of writing this answer, the above articles already use React 18 for their examples, whereas my above example still uses React 16; so the syntax regarding ReactDOM is a little different. But the idea is the same.

Jest/Enzyme w/ React - "Target container is not a DOM element."

I'm trying to test that a button in a certain react component triggers a function in its parent component. I stumble upon my issue right when I import the component in my test file, so the test hasn't even run yet.
The component I import is a regular react component and is exported as:
export default connect(mapStateToProps, mapDispatchToProps)(Manager);
And in my test file I import it as:
import Manager from '../index.js';
When I run the test I get:
Target container is not a DOM element.
I know this is very little information to give but there is literally nothing else relevant as far as I can see. The component I'm testing does a bunch of things and has a render function. After a lot of reading I read that some people had a similar issue because they exported something in the same file that does ReactDOM.render. Unfortunately, this does not apply to my problem.
Any ideas?
Might have a render call somewhere in your index.js file.
You can set an additional export without connect in your Manager and then you'll be able to import it in your test file and test its behavior:
export default connect(mapStateToProps, mapDispatchToProps)(Manager);
export { Manager };
Then in your test file:
import { Manager } from 'your-path'; // now a named import without Connect

React renders unnecessary components

In this simple Create-React-App application , I have a simple, static, Header component. For readability the header is held in a separate component. When using : Dveloper Tools - React - and selecting heighlight updates, I'm surprised to see that the Header component renders each time the destination changes. Of course this happens because the state of the parent, the App component, changes.
It was originally build as a functional component; I tried changing it to a React.pureComponent and React.Component with a 'shouldComponentUpdate' function that returns false but it did not help - the component still gets updated/rendered.
I guess this gets to the 'Virtual Dom' and does not render to the actual dom, but in more complicated apps it is still costly. Any suggestions?
Code
Update
I've forked the original repository to demonstrate the issue. In this example the Header component is build with React.Component and shouldComponentUpdate returns false. Yet the header renders each time the destination changes.
Code
When returning false from the ShouldComponentUpdate method React does not run the render method. I confirmed it by adding a console.log command.
However Chrome’s React extension - heighlight updates - still heiglights the Header. The reason for it might be that Header is a sub-component of the App Component, and since the render method of App runs, the Header is heighlighted.
The simplest solution I can think of is to convert your App component to a simple wrapper component around ControlPanel and presentation. Create a new App component which includes the Header and Footer, along with the wrapper component. Please ensure that the App does not have any state of it's own, to avoid re-renders.
My suggestion is to not worry about it, just keep your render functions as cheap as possible and let React do its work.
If you take care to just pass inn the needed props to any component, keep the components as simple as possible and in a sane structure, and make any expensive calculations outside the simple components (to keep them between state changes), that's all the optimizing I would do.
Currently Header is not a component that can implement shouldComponentUpdate.
Implement Header like this:
import React from 'react'
import '../App.css'
import globeLogo from './globe.svg'
export default class Header extends React.Component{
shouldComponentUpdate(nextProps, nextState) {
//compare props and state if need to and decide whether to render or not
//Other wise just return false;
}
render(){
return (
<div className="App-header">
<img src={globeLogo} className="App-logo" alt="logo" />
<h1>Choose My Next Destination</h1>
</div>
)
}
}
Hope that will resolve your query :)

How do I use React classes now in Ruby on Rails with WebPack

So I followed this tutorial to understand the react syntax using it on Ruby on Rails and got it pretty well, just javascript, then I tried to implement webpack from this other tutorial but the thing I noticed is that, the .jsx components has a very different syntax, also I tried to copy-paste my components from the first tutorial and doesn't work, React.createClass is no longer and now I don't know how to nest .jsx like in the first tutorial, I don't know if it is a different kind of React or where can I find examples
The JSX syntax can be a little confusing at first, but it'll become second nature soon enough. Let's say you have the react component List:
import React from "react";
import ReactDOM from "react-dom";
import Item from "./item";
export default class List extends React.Component {
render(props) {
return <ol>{props.list.map( item => <Item item={item}> )}</ol>
}
}
Notice the line that imports Item. Once you've imported your component like that, you render it exactly like you would a normal HTML element. Does this answer your question?

Categories