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

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

Related

How to pass data with Html Attributes after mapped Array without using another React components?

I am trying to pass data with HTML attribute without using another component to handleClick but I couldn't handle can anyone help me please
const handleLiClickFirst = (airport) => {
setFirst(airport.target.innerHTML);
console.log(airport.target.lat); // I can't read the data here
};
<div className="header__first">
<TextField
id="outlined-basic"
label="From"
variant="outlined"
value={first}
onChange={(e) => setFirst(e.target.value.toLocaleLowerCase())}
/>
<ul>
{resultFirst.airports?.map((airport, i) => {
return (
<li
key={airport.iata}
airport={airport}
onClick={handleLiClickFirst}
lat={airport.latitude}
name={airport.name}
long={airport.longitude}
>
{airport.name} // I can read the data here
</li>
);
})}
</ul>
</div>
Random attributes like airport and lat aren't valid to attach to a native HTML element like <li>. However, you should be able to use data attributes instead to store data on an HTML element.
And you will likely need to use data-airport={JSON.stringify(airport)} instead of just passing the JS object. And if you can avoid passing the entire object in, (by saving each of the properties that you need separately, like you are already doing with latitude, for example) that may be best to avoid to prevent creating massive HTML attribute strings.
I solve this problem without attributes and the handleClick Method after I couldn't reach the data. I removed handleClick from onClick and added the code in onClick
onClick={() => {
setFirst(airport.name);
// setFirstLatlong([airport.latitude,airport.longitude]);
setFirstLatlong({
lat: airport.latitude,
long: airport.longitude,
});
}}
#Jacob K I will try to use your method on an upcoming project. Thank you

I want to pass an HTMLDivElement as a React child. Is that impossible?

Context
I am building a React app (rails-react) where I have a parent component GameTracker that has some child components; namely, EquipmentPanel and PinnedPanels. I have added a pinned-panels-container div in the parent component where I want to move panels from the EquipmentPanel when I click on a 'pin' button.
<div id='container'>
<EquipmentPanel pinPanel={this.pinPanel}/>
<div id='tracker-contents'>
{this.state.pinnedPanels.length > 0 &&
<div id='pinned-panels-container'>
<h2>Pinned Panels</h2>
{this.state.pinnedPanels}
</div>}
</div>
</div>
Approach
The way I plan to do this is create a pinPanel() function in the parent component GameTracker, and pass it as a prop to its child, EquipmentPanel. The child then adds the button, and calls pinPanel(div), with div being the specific div/panel I want to pin.
pinPanel(panel) {
let newPanel = panel.current.cloneNode(true)
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(newPanel.innerHTML, 'text/html');
newPanel = htmlDoc
let newPinnedPanels = this.state.pinnedPanels
newPinnedPanels.push(newPanel)
this.setState({
pinnedPanels: newPinnedPanels
})
}
Error
Now, whenever I pin a panel, React gives me:
Uncaught Error: Objects are not valid as a React child (found: [object HTMLDocument]).
If you meant to render a collection of children, use an array instead.
If I try to use an array, as the error message recommends, I get the same error. If I don't use DOMParser(), (which I found here), I get the same error, with the following difference: found: [object HTMLDivElement].
My question is, is there any way in React to clone a div with all its contents, pass it to another component through state, and render it in another component that is not its parent or child? I basically want to copy/paste a div.
Edit: If I try to assign it by .innerHTML, the end result is a panel with [object HTMLDocument] as a string inside.
Unsure if this is considered a proper answer, but I made it work with DOM manipulation. Feels hacky, but it works. If someone has any insight, it is of course welcome.
let newPanel = panel.current.cloneNode(true)
if (this.pinnedPanelsRef.current.innerHTML.includes(newPanel.children[0].innerHTML)) {
this.pinnedPanelsRef.current.innerHTML = this.pinnedPanelsRef.current.innerHTML.replace(newPanel.children[0].innerHTML, "")
}
else {
this.pinnedPanelsRef.current.innerHTML += newPanel.children[0].innerHTML
}
I still feel like there is a much more elegant solution that I am failing to reach.

.innerText of an element is not showing up

I have a div that is contenteditable and grabbing the div using useRef(), which is a reactjs hook.
When I try to display the text inside the contenteditable div, the alert shows nothing but the log shows the text.
Is there something I am missing?
this is just a snippet I created
export default function Input() {
const inputRef = useRef();
const showText = () => {
console.log("text: ", inputRef.current.innerText);
alert("text: ", inputRef.current.innerText);
}
return (
<>
<div ref={inputRef} contentEditable="true" supressContentEditableWarning={true} />
<button onClick={showText}>Show text</button>
</>
)
}
It also does't work when I use it as a value inside an object eg.
const obj = {
text: inputRef.current.innerText
}
I will be thankful if someone can help me understand what is going on here!!
UPDATE
just don't use alert to debug lol.
Is there anything stopping you from getting the innerText using DOM like this-
var innerText = document.getElementById('elementName').innerText
then passing the value to your reactJS?
window.alert only takes a single parameter, so only the first string is shown. If you pass in too many arguments to a javascript function, the extra parameters will simply be ignored. This is different from console.log, which is a variadic function, meaning it will take any number of parameters and display all of them.
Try alert("text: " + inputRef.current.innerText) instead.

Render React Native Elements from JSON

I have searched around...can't quite find what I'm looking for, so I appreciate any help! Here is what I am going for:
I am building a CMS-like setup for a React Native app. This is so that an admin of an app can login to the CMS dashboard, and update a page/view of the app without having to go into the hardcode. I would like them to be able to choose from a pre-set list of components and be able to drag-and-drop them into the app, in whatever order they would want and be able to update the content and colors, etc. Let me provide an example...
There is a home page that I imagine having a rotating banner at the top, then a button for a information modal, then a set of menu links to go to sub-child pages.
So what I think, development-wise, is to give the app admin a WYSIWYG type of setup, and to store the result of this in the Database. It could store in the database as:
<RotatingBanner />
<Modal />
<ContentMenu>
<ContentMenuLink title="About" />
<ContentMenuLink title="Competitive" />
<ContentMenuLink title="Recreational" />
<ContentMenuLink title="Tournaments" />
<ContentMenu />
Right now, when I try to render this into a screen, I continue to have it render that as the actual words vs the components they are representing if that makes sense. So the page looks just like the code block above, instead of seeing a rotating banner and modal, etc.
I have tried a tool to convert HTML into React Native elements...does anyone know how I can convert a fetched JSON that would look like:
{content: "<RotatingBanner /><Modal /><ContentMenu>...."}
and have it create the real components in the render function? Any other thoughts or ideas/advice on creating a CMS like this are greatly appreciated if you would like.
Thanks!
Let's say your have this JSON:
const data = {
"components": [
{"name": "component1", props: {"hello": "world"}},
{"name": "component2", props: {"color": "red"}},
]
}
Make your components and then reference them in an Object (map):
import Component1 from './Component1'
import Component2 from './Component2'
const COMPONENT_MAP = {
component1: Component1,
component2: Component2,
}
Then make your wrapper component:
const Wrapper = ({data}) => (
<View>
{data.components.map(({name, props}) => {
const Component = COMPONENT_MAP[name]
return <Component {...props} />
}}
</View>
)
VoilĂ  :)
<Wrapper data={data} />
I would recommend using Array's to save and render multiple childrens
const Component1 = () => <Text>One</Text>
const Component2 = () => <Text>One</Text>
const childs = [
Component1,
Component2
]
return childs
React is able to render arrays as they are.
Other possible solution could be,
return Object.keys(child).map(item => childs[item] )
A quick solution can be react-native-dynamic-render
Also, you can render nested components with that.
A complete example is here

How to select element inside open Shadow DOM from Document?

Say I have a DOM that looks like this in my Document:
<body>
<div id="outer">
<custom-web-component>
#shadow-root (open)
<div id="inner">Select Me</div>
</custom-web-component>
</div>
</body>
Is it possible to select the inner div inside the shadow root using a single querySelector argument on document? If so, how is it constructed?
For example, something like document.querySelector('custom-web-component > #inner')
You can do it like this:
document.querySelector("custom-web-component").shadowRoot.querySelector("#inner")
In short, not quite. The TL:DR is that, depending on how the component is set up, you might be able to do something like this:
document.querySelector('custom-web-component').div.innerHTML = 'Hello world!';
Do do this - if you have access to where the web component is created, you can add an interface there to access inner content. You can do this the same way you would make any JavaScript class variable/method public. Something like:
/**
* Example web component
*/
class MyComponent extends HTMLElement {
constructor() {
super();
// Create shadow DOM
this._shadowRoot = this.attachShadow({mode: 'open'});
// Create mock div - this will be directly accessible from outside the component
this.div = document.createElement('div');
// And this span will not
let span = document.createElement('span');
// Append div and span to shadowRoot
this._shadowRoot.appendChild(span);
this._shadowRoot.appendChild(this.div);
}
}
// Register component
window.customElements.define('custom-web-component', MyComponent);
// You can now access the component 'div' from outside of a web component, like so:
(function() {
let component = document.querySelector('custom-web-component');
// Edit div
component.div.innerHTML = 'EDITED';
// Edit span
component._shadowRoot.querySelector('span').innerHTML = 'EDITED 2';
})();
<custom-web-component></custom-web-component>
In this instance, you can access the div from outside of the component, but the span is not accessible.
To add: As web components are encapsulated, I don't think you can otherwise select internal parts of the component - you have to explicitly set a way of selecting them using this, as above.
EDIT:
Saying that, if you know what the shadow root key is, you can do this: component._shadowRoot.querySelector() (added to demo above). But then that is quite a weird thing to do, as it sorta goes against the idea of encapsulation.
EDIT 2
The above method will only work is the shadow root is set using the this keyword. If the shadow root is set as let shadowRoot = this.attachShadow({mode: 'open'}) then I don't think you will be able to search for the span - may be wrong there though.
This code will behave like query selector and work on nested shadowDoms:
const querySelectorAll = (node,selector) => {
const nodes = [...node.querySelectorAll(selector)],
nodeIterator = document.createNodeIterator(node, Node.ELEMENT_NODE);
let currentNode;
while (currentNode = nodeIterator.nextNode()) {
if(currentNode.shadowRoot) {
nodes.push(...querySelectorAll(currentNode.shadowRoot,selector));
}
}
return nodes;
}