use plugin International Telephone Input in react - reactjs

I'm very new to react and I just want to use this https://github.com/jackocnr/intl-tel-input plugin in my form. But in the documentation says to use pure js input id query selector to use plugin. But how can I change this kind of code to react usage.
code example in doc:
<input type="tel" id="phone">
<script src="path/to/intlTelInput.js"></script>
<script>
var input = document.querySelector("#phone");
window.intlTelInput(input);
</script>

You should avoid to use Jquery in React projects. You can do it React way.
For intl-tel-input, there is react-intl-tel-input and react-intl-tel-input-v2 packages are available.
import ReactIntlTelInput from 'react-intl-tel-input-v2';
import 'intl-tel-input/build/css/intlTelInput.css';
<ReactIntlTelInput
value={this.state.value}
onChange={this.onChange}
/>
Demo

It's not a good idea to manipulate the DOM manually since react creates a virtual DOM for performance issues
React creates a tree of custom objects representing a part of the DOM.
For example, instead of creating an actual DIV element containing a UL
element, it creates a React.div object that contains a React.ul
object. It can manipulate these objects very quickly without actually
touching the real DOM or going through the DOM API. Then, when it
renders a component, it uses this virtual DOM to figure out what it
needs to do with the real DOM to get the two trees to match.
You can think of the virtual DOM like a blueprint. It contains all the
details needed to construct the DOM, but because it doesn't require
all the heavyweight parts that go into a real DOM, it can be created
and changed much more easily.
source
There's a lot of "ready-made" react components that you can use. You can use react-phone-number-input for example like this:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "react-phone-number-input/style.css";
import PhoneInput from "react-phone-number-input";
import "./styles.css";
function App() {
const [inputValue, setInputValue] = useState("");
return (
<div className="App">
<h1>International phone number</h1>
<PhoneInput
placeholder="Enter phone number"
value={inputValue}
onChange={inputValue => setInputValue(inputValue)}
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Take a look at codesandbox
If you want to learn more about how React manipulates the DOM, you can read this article.

Related

React: why set the document title inside useEffect?

I just watched a talk from React Conf 2018. In the video, the speaker shows 2 ways to set the document title. The first is by using the Lifecycle methods (componentDidMount and componentDidUpdate) if we use a class component, the second one is by using the useEffect hook if we use a function component. It looks like that's the recommended way to do it according to answers from this question.
But, I tested the following code and it seems to work just fine to set the document title directly:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
document.title = 'wow'
return <p>Hello</p>
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
The title changed:
Is there any significance of setting the document title inside useEffect or componentDidMount?
Or is it because it was the only way to set the document title?
Is it okay to set the document title directly like I did in the snippet above?
Update:
It also works with class component:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
document.title = 'wow'
return <p>Hello</p>
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
The thing is, the render function in React, is considered to be a pure function.
A pure function should not have any side-effects. Eventually updating the document.title means that you are referencing the document directly from render-> which is already considered a side effect.
Render should mainly do one thing -> render some JSX, if there is a need to do some API calls/interact with the document/window etc..., this should be placed in componentDidMount/componentDidUpate for a class Component, OR in a useEffect/useLayoutEfect for a functional component based on hooks.
(useEffect for e.g. is a function that runs asynchronously, and updating the document title from it will not block the rendering, whereas doing it directly will block it.)
Use react-helment which is also widely used in other frameworks with the same name as helmet express ...
Here is the same code:
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://example.org/example" />
</Helmet>
...
</div>
);
}
};
Another way to use via props to which is cleaner IMO
...
<Helmet titleTemplate={`%s | ${props.title}`} defaultTitle={constants.defaultTitle} />
You may also use react-helmet-async for more features.

Whats the difference between React render and React-DOM render

EDITED because my original question was not worded right.
I'm trying to understand why ReactDOM is being used to render some HTML divs, and other rendering is done in React. Is there something I'm missing here?
An example from a React course I took recently, this is the code in one of the exercises that uses react-dom:
import React, {Component} from 'react'
import {render} from 'react-dom'
var Bookstore = [
{"title":"Mr. Bean", "author":"Rowan Atkinson", "pages":200},
{"title":"The only Bean", "author":"Chris Dowd", "pages":100},
{"title":"IT crowd", "author":"Rich Ayando", "pages":50}
]
const Book = ({title, author, pages}) => {
return (
<section>
<h1>{title}</h1>
<h3>By {author}</h3>
<p>{pages} pages</p>
</section>
)
}
const Library = ({bookstore}) => {
return (
<div>
{bookstore.map(
(book, i) => <Book key={i} title={book.title} author={book.author} pages={book.pages}/>
)}
</div>
)
}
render(
<div>
<Library bookstore={Bookstore} />
</div>,
document.getElementById('root')
)
While another React file renders this way:
import React, {Component} from 'react'
export const Book = ({title="No title", author="No author", pages=0, freeBookmark}) => {
return (
<section>
<h1>{title}</h1>
<h3>By {author}</h3>
<p>{pages} pages</p>
</section>
)
}
What happens in the real DOM ?
Each time something in the DOM changes. Since DOM is represented as a
tree structure, changes to the DOM is pretty quick but the changed
element, and it’s children’s has to go through Reflow/Layout stage and
then the changes have to be Re-painted which are slow. Therefore more
the items to reflow/repaint, slower your app becomes.
To overcome this react uses virtual DOM
How virtual DOM helps?
it tries to minimize these two stages to get better performance.
virtual means a representation of a UI is kept in memory and synced with the "real" DOM by a library such as ReactDOM.
Difference between render in the component & reactDOM.render ?
Render in the component is used to construct the virtual DOM.
reactDOM.render is used to attach the virtual DOM tree to the real DOM tree after the diffing algorithm detects the changes.

React Convert HTML to Component and pass extra props

I'm using [svg-inline-loader][1] to inline SVG Images in my React Application.
When I import an SVG, the webpack module passes it to the variable as an HTML string. I need to convert this string into a React Component so that I can pass additional props to it.
My current code looks like this
import SVGlogo from './logo.svg';
export default () => (
<a href="/" className="navbar-item is-purple" dangerouslySetInnerHTML={{ __html: SVGlogo }} />
);
This works fine but I need to pass additional attributes/props to SVGlogo. Is there a way I can do this elegantly without manually modifying the string and adding attributes to it.
I highly recommend to built an own non class component for your SVG stuff and then import it into the section / HOC component.
See my example here:
Greetings!

Rendering default HTML and CSS to Sketch with react-sketchapp

I've was testing the react-sketchapp which looks pretty neat so far.
Besides rendering the default sketch elements like Text,View,Image and so on, would it be possible to render a default react component containing HTML-Markup styled with scss?
I tried rendering the following Hello-Component:
import React from 'react';
import { render, Artboard, Text, View } from 'react-sketchapp';
const Hello = () => (
<View
name={`Hello View`}
>
<Text name="Hello Text">
<span>Hello World</span>
</Text>
</View>
);
const Document = () => (
<Artboard
name="Hello Board"
>
<Hello />
</Artboard>
);
export default (context) => {
render(<Document />, context.document.currentPage());
}
but I get the following error:
Could not find renderer for type 'span' flexToSketchJSON
Is rendering default react components including html / css to Sketch possible?
You can't render HTML elements to Sketch, same as you can't render HTML elements to React Native.
React is just a way of managing a tree of abstract components. How to render these components needs to be defined by the specific renderer you are using. react-sketchapp is a renderer that understands components which render to Sketch elements, but it does not understand HTML elements such as div. (and React Native includes a renderer which knows how to render React Native components to native mobile views, react-music is a renderer which knows how to render React Music components into audio, and so forth).
React, in and of itself, has nothing to do with HTML elements or the DOM. The react-dom renderer library is where the magic of rendering into the DOM happens. If you want to render HTML elements to Sketch, you'll need to write a React renderer which knows how to convert HTML elements to Sketch's file format.
You can export any HTML/CSS to Sketch using html-sketchapp.
It is possible.
Try looking into using React-Primitives with React-SketchApp.
https://github.com/lelandrichardson/react-primitives
It's in a few examples within React-SketchApp e.g.
https://github.com/airbnb/react-sketchapp/tree/master/examples/profile-cards-primitives

Keep valid HTML markup for "render()" for dynamic value as attribute

I am reading React and not happy to keep the valid HTML markup for render() function. Following is code snippet.
Working Code:
import React from "react";
export default class Header extends React.Component {
render () {
const title="I am title";
return (
<img title={title} src="./test.png"></img>
)
}
}
Not working Code when used valid HTML markup (title value with double quote):
import React from "react";
export default class Header extends React.Component {
render () {
const title="I am title";
return (
<img title="{title}" src="./test.png"></img>
)
}
}
I want to keep valid HTML markup to keep my development easy and easy to trace if any HTML markup issue.
Is there any way to use the dynamic attribute value with double quote?
You don't have to care about that. JSX is compiled to JS syntax which render HTML for you. We can consider it as a second abstraction layer over HTML.
Moreover, there are a lot of differences between HTML and React's components implementation.
Closing textarea HTML:
<textarea />
Closing textarea JS:
<textarea></textarea>
The same about setting attributes, you wont be able to have it valid.
But the most important that, you should understand that it is an abstraction layer. That is why some people are propagating against JSX, because a lot of peopleand confused. So they promote using plain JS using hypescript(see right part).
Here is a nice article about that.

Resources