Why react use angular brackets in rendering the component - javascript

I am new to the react as my background is ruby, so maybe it look a silly or noob question.
i come to the article
"Every component must begin with a capital letter. And once a component is declared, it can be written and used very similarly to an HTML element." and also this
"To use this component in your application, use similar syntax as normal HTML: "
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
root.render(<Car color="red"/>);
we have a car component created using class component so my question here is Why we use angular bracket here for creating instance of Car class. is this a syntax of creating instance of class in react.
Or
To use this component we have to use similar syntax as HTML. why?

React uses angular brackets () in rendering an element as a result it permits you to incorporate the element as a JSX part. JSX may be a syntax extension for JavaScript that permits you to write down HTML-like code in your JavaScript files. it's not obligatory to use JSX with React, however, it's a preferred alternative, as a result, it makes it easier to grasp the structure of your elements and the way they relate to the DOM.
To render an element in React, you'll use the ReactDOM.render() methodology and pass it to the element you wish to render further as a DOM part.
import React from 'react';
import ReactDOM from 'react-dom';
const MyComponent = () => <h1>Hello, World!</h1>;
ReactDOM.render(<MyComponent />, document.getElementById('root'));
The MyComponent operation is wrapped in angular brackets () and passed to the ReactDOM.render() methodology as a JSX part. This tells React to treat the operation as an element and render it within the DOM part with the id of the root.

Hopefully this helps. Before React we needed an index.html File and had to call your javascript.js file within your HTMLenter image description here. example: in HTML, if we wanted to select a Button in javascript and add an onClick event we had to call the button but be specific as possible, so we had to add a class,ID, etc... Import your button to your javascript file like car= document.getElementById("car1")
and then add a onclick event. as you can see this can be exhausting. worst part is you cant add HTML in your Js file, so no tags, etc.. so the way to make things easier in HTML is adding brackets. React allows you to use HTML and Js syntax.
in your example: return I am a {this.state.color} Car!;
we are telling React we have h2 from HTML but anything within { } is Javascript. as you can see React just makes easier to use HTML and javascript in the same file

Related

Creating refs outside of component. Is that a bad practice?

I am working on a library which requires exporting a couple of functions for users to call upon. Those functions need access to component ref in order to add/remove classNames and auto scroll etc.
I was able to get it to work by moving my ref (created by React.createRef) outside of the component itself (NOT talking about defining it outside of the constructor but inside the component)
Here's how my code looks like (used a class component instead of functional as the hook useRef obviously can't be used outside)
import React, { PureComponent, createRef } from "react";
import { typingEffect } from "../redux/actions/dispatch";
import { containerRef } from "./Container";
let typingRef = createRef();
export async function displayTypingEffect() {
await typingEffect();
typingRef.current.className += " rcb-is-typing";
containerRef.current.scrollTop = containerRef.current.scrollHeight + 700;
}
export function hideTypingEffect() {
typingRef.current.className = "rcb-typing-container";
containerRef.current.scrollTop = containerRef.current.scrollHeight + 700;
}
export default class Typing extends PureComponent {
render() {
return (
<div ref={typingRef}>
rest of the component code which is unnecessary for this question
</div>
)
}
I am just wondering if there's a possibility of any unforeseen issues or bugs if I follow this pattern.
Thank you.
This makes the typingRef
a global variable (inside the module), and
be created outside of any React life cycles
typingRef will be the same object for every instance of the Typing component, i.e. if two components are created from the Typing class, both will write to the same typingRef. Your API will provide access some DOM element, but you can not be sure which one it currently is.
typingRef is created as soon as the file is imported, before React even starts, and will live for the life time of the Javascript code, not the life time of any React component.
I think (not 100% sure) any DOM elements referenced by typingRef will be kept (at least) until typingRef gets overwritten (or the Javascript execution is ended). So if a Typing component gets unmounted, the DOM element (and everything that's connected to it) is still kept in memory. So your API will provide access to "useless" DOM elements.

Where to add a function in React classes - before render() vs in render() vs outside of the class

#1 - when to add code on the class?
class WrappedHorizontalLoginForm extends React.Component {
#2 - when to add code on the class?
handleFormSubmit = (event) => {
event.preventDefault();
const user = event.target.elements.user.value;
console.log(user)
};
render() {
# 3 - when to add code in the render?
return (<div>
<Form onSubmit={this.handleFormSubmit}>
</Form.Group>
</div>
Can someone kindly point out cases on when to add a function in the class vs when to add code within the render method vs when to add it outside the class?
Are their generic guidelines to follow in terms of functionality or specific code?
handleFormSubmit in the code above can be used as an example to explain.
Any code in the render method will run when the component rerenders due to a change in state or props etc. So say you have a component which shows a table of data from a database and it has some state of which cells are selected etc. You would not want to run the database get query when you select a cell as it is not changing. So for that you would have the database request in something like componentWillMount rather than in the render method.
Generally code in the render method is for things such as defining temporary variables or if and else clauses. You want to write most code in the designated react class methods.
Also writing thread blocking code in the render method will reduce the speed of your site.
There is no need to put code just before the render method execution - you probably want to use the component life-cycle methods instead.
if you wants to keep working with Classes so you can use the componentWillMount that will execute just before the component is mounted into the dom.
if you want to work with Functional Components so as part of React 16.8 there is a new feature that called React Hooks.
You can read more about it here: https://reactjs.org/docs/hooks-intro.html

React Component without Function or Class?

On occasion, I have both seen and wrote some React code like this.
const text = (
<p>
Some text
</p>
);
This does work, but are there any issues with this?
I know I can't use props this way, but if all I'm doing is rendering something simple like a paragraph, I don't see why I would need to make it a functional component or extend React.Component
My current reason for this is because I need to pass in a paragraph or two as placeholder text and I can't just pass in plain text.
This is not a react component, it is just a variable in which JSX is stored:
const text = (
<p>
Some text
</p>
);
As per DOC:
const element = <h1>Hello, world!</h1>;
This funny tag syntax is neither a string nor HTML.
It is called JSX, and it is a syntax extension to JavaScript. We
recommend using it with React to describe what the UI should look
like. JSX may remind you of a template language, but it comes with the
full power of JavaScript.
props will be available only in React component, either in Functional Component or a Class based Component.
Why React is required in this if it is not a react component?
We can store JSX in any variable and it will get transpiled by babel, and get converted into React.createElement.
As per DOC:
JSX just provides syntactic sugar for the React.createElement()
function.
Since JSX compiles into calls to React.createElement, the React
library must also always be in scope from your JSX code.
Example: when we write:
var a = <div> Hello </div>
Result of this will be:
var a = React.createElement(
"div",
null,
" Hello "
);
This code is just storing a paragraph element with the text inside it into the variable text. It's not a component, functional or otherwise. Use it in a React component like you would standard Javascript:
render() {
return (
<div className="some-text">
{ text }
</div>
);
}

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).

How do I render a string as children in a React component?

Take a simple component:
function MyComponent({ children }) {
return children;
}
This works:
ReactDOM.render(<MyComponent><span>Hello</span></MyComponent>, document.getElementById('stage'));
but this doesn't (I removed the <span/>):
ReactDOM.render(<MyComponent>Hello</MyComponent>, document.getElementById('stage'));
because React tries to call render on the string:
Uncaught TypeError: inst.render is not a function
On the other hand, this works fine:
ReactDOM.render(<p>Hello</p>, document.getElementById('stage'));
How do I make <MyComponent/> behave like <p/>?
If you're using React 16.2 or higher, you can do this using React fragments:
const MyComponent = ({children}) => <>{children}</>
If your editor doesn't support fragment syntax, this will also work:
const MyComponent = ({children}) =>
<React.Fragment>{children}</React.Fragment>
Keep in mind that you're still creating & returning a component (of type MyComponent) as far as React is concerned - it just doesn't create an additional DOM tag. You'll still see a <MyComponent> tag in the React Debug Tools, and MyComponent's return type is still a React element (React.ReactElement).
Well the difference is <p> is an html element and MyComponent is a React Component.
React components need to render/return either a single component or a single html element.
'Hello' is neither.
You need at least one top-level HTML element. Your component can't really just output a string, that's not how React works.
The simplest solution is to simply make your MyComponent wrap it's output in a span or div.
function MyComponent({ children }) {
return <span>{ children }</span>;
}
Currently, in a component's render, you can only return one node; if
you have, say, a list of divs to return, you must wrap your components
within a div, span or any other component.
source
And what you are returning is not a root node. You are returning a react component that is returning a string where it should be returning an HTML element.
You can either pass your string already wrapped with an HTML element (like you already did in your example) or you can wrap your string in a HTML element inside your "MyComponent" like this
function MyComponent({ children }) {
return <span>{ children }</span>;
}
React can render either React components (classes) or HTML Tags (strings). Any HTML tag is by convention lowercase where a Component is Capitalized. Every React component has to render exactly one Tag (or null). To answer your question: you cannot.
In the example above, you render what's given with the children attribute where this will render the tag inside or a string that is not valid.

Categories

Resources