What is the difference between document.createElement('div') and React.createElement('div')? - html

str = "<p> this is paragraph </p>"
The above str can consist of any elements of HTML. So to get he text I have used the below code in my react application.
let descriptionDiv = document.createElement('div');
descriptionDiv.innerHTML = description;
description = descriptionDiv.textContent || descriptionDiv.innerText;
Do I need to use ReactDOM in this scenario ?
Like: React.createElement('div');
But I don't know whether when to use it ? Is it safe to accessing dom directly?

JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI
In html it's just creating another node to dom.
If you want to access dom while using react you can use ref
To access the DOM pass a ref with the react element and latter access it with findDOMNode method
It's completely safe to use dom api directly but it depends what is your requirement... simple or you have some complicated tasks ,prefer to use ref in react
example
import ReactDOM from 'react-dom';
...
let reactElement = ReactDOM.findDOMNode(this.refs.refName)
...
<Component ref='refName'/>

React.createElement
React.createElement(
"button",
{
className: "panel-btn-open"
},
"Open"
),
document.createElement
const buttonOpen = document.createElement('button');
buttonOpen.classList.add('panel-btn-open');
buttonOpen.textContent = 'Open';

Related

Custom Styled Input field in react js

I am looking for input field which take the input in formated way based on user selection of font, bullets and code type.
Provided the image below
Code should be in React Js and output can be html in json format
You're trying to say you need to implement a rich text editor using React?
Well, in that case I personally use jodit-react because it's open-source, works well with TypeScript and NextJS and outputs the text in HTML format. You can find the project here and basic implementation looks like this.
import React, {useState, useRef, useMemo} from 'react';
import JoditEditor from "jodit-react";
const Example = ({placeholder}) => {
const editor = useRef(null)
const [content, setContent] = useState('')
const config = useMemo({
readonly: false // all options from https://xdsoft.net/jodit/doc/,
placeholder: placeholder || 'Start typing...'
},
[placeholder])
return (
<JoditEditor
ref={editor}
value={content}
config={config}
tabIndex={1} // tabIndex of textarea
onBlur={newContent => setContent(newContent)} // preferred to use only this option to update the content for performance reasons
onChange={newContent => {}}
/>
);
}
Take a look at this example below.
Hope this helps!
Cheers!

How to render an element in React which was created by createElement()?

I have created an image element by using:
const image = document.createElement('image'); // or new Image();
How can I render this image variable in React ?
I don't want to use Html tags to do something like this:
<img src={image.src} ... />
Is there any other way ?
Well either create a <div class="parent"> </div> and then use
document.querySelector(".parent").appendChild(imageElement)
or simply,
document.appendChild(imageElement)
This is the wrong way to go about doing this. You shouldn't directly manipulate the DOM with React. I would instead have an array of objects in your state, and in your component, map the objects to the elements of your choosing. Like this
const Component = () => {
const [components, setComponents] = useState([{src:'path/to/src', alt:'altTag'}])
return(
<>
{
components.map(e => {
return(<img src={require(e.src)} alt={e.alt} />)
})
}
</>
)
}
Wrote this from memory/without testing so there might be something wrong so dont kill me. But if you need to render it anywhere, make it its own component. If it's truly just one image, then you don't need the array/map just use an object and render it same way

How to bind value to be displayed in html in React?

I just created my first test in React.
Following an example of a tutorial I have created several buttons that activate a function by which they receive the index of the selected button. The first button selected must show one of the operators of the aray and the next one the opposite, and so on...
const operators = ['+', '-'];
const placeHolder = 'o';
function Boxes(props){
return (
<AppContext.Consumer>
{context => {
const value = context.boxes[props.index];
const icon = value !== null ? operators[value] : placeHolder;
const isDone = icon !== placeHolder ? 'done' : '';
return (
<button className="box-active"
onClick={() => context.boxAct(props.index)}>
{operator}
</button>
)
}}
</AppContext.Consumer>
)
}
and here is de function
boxAct = (index) => {
if (this.state.boxes[index] === null) {
this.state.boxes[index] = '+';
}
}
How can I achieve this? Following the steps of the example I only get the placeholder value in all the buttons and I can't get them to change.
What am I doing wrong?
thanks for your help
Functional components are different from class components. As you can read from official documentation react components.
Your Boxes component is declared as functional component. this.state syntax is valid just inside class component. In that case correct way to update state would be to call this.setState(<newstate>) function avilable to all class components. You can read more here react state.
You can provide state to functional components via hooks. In particolar useState hook. Here is explained how to do useState hook.
In your case (functional component) you can dop like this:
import hook with:
import React, { useState } from 'react';
then you need to initialize boxes state like this
const [boxes, setBoxes] = useState(context.boxes)
The function you will set as onClick handler is:
boxAct = (index) => { if (boxes[index] === null) {
let newBoxes = boxes;
nexBoxes[index] = '+';
setBoxes(newBoxes);
}
}
Be aware also that you should not pass data via context api, context api is used to provide global information such as application language or theme. Read more here react context

Is it possible to copy an object's properties from one component and display them in another component using refs?

Say I have 2 components. One is a table with a list of stores. Each store has properties like color, item, open, closed. The other component is one to create a store.
I want to be able to click on a little copy icon on one of the created stores already, and take that information to the create store component, and populate that component with the properties in order to make changes and create a completely new store.
Is this doable using refs? Or is there a better way of doing this?
Use ref to this task is a mistake. React works using a Virtual DOM that is a cleaner and faster Object Tree with information that will be through to DOM by React DOM the REF API is used to access direct the DOM information, and you don't need any information from DOM to do ur task.
https://reactjs.org/docs/refs-and-the-dom.html
A way yo do what you describe is create a state/setState on the parent component and pass a state for the store component and a setState to the table component for example:
import React, { useState } from 'react'
const StoreComponenet = ({ color, item, open})=>{
// logic of component
return (
<div>
// ...
</div>
)
}
const TableComponent = ({ setStore })=>{
// logic of component
return (
<table>
<tr onClick={() => setStore("blue", {id: 2, name: "BlueStore" }, false)}>
Build blue store
</tr>
...
</table>
)
}
const App = ()=>{
const [store, setStore] = useState(null)
return (
<TableComponent setStore={setStore} />
{
store &&
<StoreComponent
color={store?.color}
item={store?.item}
open={store?.open}
/>
}
)
}

Two way binded data appears as string in Polymer

I am trying to render polymer template using below code,
const shadowRoot = this.attachShadow({mode: 'open'});
const htmlTemplate = importDoc.querySelector('template');
shadowRoot.innerHTML = htmlTemplate.innerHTML;
But this renders two way binded data also as a string instead of showing the binded value e.g
<h1 id ="contactFooter">{{localize('_testVal')}}</h1>
is displayed as it is do anyone have any idea? Two way binding is just example it renders everything like this.
To use a <template> tag you should use importNode on the content.
e.g.
var clone = document.importNode(htmlTemplate.content, true);
shadowRoot.appendChild(clone);
// note that you will need to clear the shadowRoot if you do rerenderings
// OR you could try
shadowRoot.innerHTML = htmlTemplate.content;
see more details here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template