React Component without Function or Class? - javascript

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>
);
}

Related

Why react use angular brackets in rendering the component

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

Appending JSX in React Native

I'm searching for a way to add a JSX element programmatically in React Native. Not conditionally.
It needs to be independent function, so far I couldn't find anything about this. Let me give you code example;
const appendJSX = () => {
const jsx = <Text> Hello! </Text>
append(jsx) // <---- can we do something like this?
}
let's say I call this function with useEffect and it should add whatever jsx I have inside the function. Up until this point I always see things like pushing inside of an array or something like that.
UPDATE
Equivalent behaviour that works on web;
useEffect(() => {
const div = document.createElement("div");
div.innerText = "appended div"
document.body.append(div)
}, [])
As you can see we don't have to touch any JSX in application. Reaching document.body and appending whatever we want is possible in React Web. But how can we achieve this in React Native?
Not quite sure what you want to do, but as for to add a JSX manually. Here's the answer.
JSX is already part of the language in most of the cases.
const a = <Text />
export default a
Will translates into:
const a = createElement(Text, null, null)
export default a
Therefore in most of common cases, if you continue using React somewhere else, then the variable a holds a React element without any compilation error.
You might wonder what a actually really holds, it's an object:
const a = {
$$typeof: Symbol(ReactElement),
props: null,
type: Text
}
So you can see the only dependencies in above piece is Text and the ReactElement Symbol. As long as you can resolve them, you are good to export this to anywhere. The latter is normally taken care by Babel.
NOTE:
There's a difference between Text and <Text />. If you just want to export a Text which is a function component, there'll tutorial online, also you can dig into any third party library, because essentially that's what they do, export Text so other people can use it.

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>
);
}

What is the use of components in ReactJS instead of a single variable

I started to study ReactJS and can't understand the purpose of components. for instance lets have a component:
var QuoteMaker = React.createClass({
render: function () {
return (
<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="#">
Douglas Huebler
</a>
</cite>
</blockquote>
);}});
why can't we just use
var thisVar = (
<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="#">
Douglas Huebler
</a>
</cite>
</blockquote>
)
instead of that component.
You could. That would be just fine.
What you couldn't do is have a list of those, built from dynamic data.
What if you wanted multiple quotes from multiple people?
What if you wanted a button that randomized which quote appeared?
What if you wanted a twitter feed, or a blog roll, or a comment section?
You don't necessarily need the createClass. That's a particularly old way of looking at things, and you should really be using a Babel build pipeline; full stop.
You can simply say:
const Quote = (props) => (
<blockquote>
<p>{ props.quote }</p>
<cite >{ props.author }</cite>
</blockquote>
);
ReactDOM.render(<Quote quote="..." author="..." />, rootEl);
Now you can happily build a randomizer, or a quote API, or a quote editor, or whatever. The component does what it should, and it leans on input from the outside world for what it shouldn't do.
React allow you to get a composant approach. So you can use as a new balise text (composant) in react. You can reuse this component, it will have the same behavior everywhere.
Functional components
That way that you have in example can be created function, or stateless components, where we can use props object, that can be passed from the parent object.
const Component = (props) => {
//access to props
}
Class component
Class components allows to store thier own state and use it to rerender the component, via this.setState() function:
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
//access to both state and props
}
Why we must use components instead of js objects? Because react has its own DOM - virtual DOM, where it listening to changes and rerendering your real DOM, you can reuse or extend this component anywhere and its also semanticly awesome.
Take a look to the documentation about React components.
There are lots of uses for components. These are few:
Allegedly, if your component has no logics or special use, just flat html, so can pass using component, although it is more encapsulated and looks more neat.
If now or in the future you'll want to use some logics for your component, so it can be handled in the component. That is the Object Oriented approach for using html block of code. If your'e coming from Angular, you can think of it as "directive", from .Net "User control". Well, not exactly, but the purpose is same.
Calls and uses to different libraries. It is a better practice not to require libraries as global variable, but only for your use in the component.
And of course the most important factor: You can take advantage of the react "digest loop". You can choose what to do on constructing, before rendering, after rendering, and much more.
You can look it up here: https://facebook.github.io/react/docs/react-component.html
As i said before, there are lots of uses for components over flat html, and basically this is the whole point of ReactJS as component based :)

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