How to create dynamic element in react? - javascript

I am trying to create dynamically element on button click and append it to one of the classes by using ref.
I can use document.createElement but from what I read do not use it in react
For example I want to add an element of <p> to div with class name of classes.elements by clicking the button
import React, { useRef } from 'react'
import classes from './AddElement.scss'
const AddElement = (props) => {
const elementRef = useRef(null)
const addElement = () => {
<p>This is paragraph</p>
}
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div ref={elementRef} className={classes.elements}>
</div>
</div>
)
}
export default AddElement;

You could try using the useState hook like this :
import React, { useState } from 'react';
import classes from './AddElement.scss';
const AddElement = () => {
const [dynamicElems, setDynamicElems] = useState([]);
const addElement = () => {
// Creates the dynamic paragraph
const newDynamicElem = <p className={classes.elements}>This is paragraph</p>;
// adds it to the state
setDynamicElems(() => [...dynamicElems, newDynamicElem]);
};
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div className={classes.elements}>{dynamicElems}</div>
</div>
);
};
export default AddElement;

const AddElement = (props) => {
const [dynamicCompList, setDynamicCompList] = useState([]);
const addElement = () => {
const dynamicEl = React.createElement("p", {}, "This is paragraph");
setDynamicCompList(dynamicCompList.concat(dynamicEl));
}
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div className={classes.elements}>
{dynamicCompList}
</div>
</div>
)
}
export default AddElement;

Try this:
const addElement = () => {
const para = document.createElement("p");
para.innerHTML = 'Hello';
elementRef.current.appendChild(para);
};
<div ref={elementRef}></div>
<button onClick={addElement}>Click me</button>

Approach 1
import React, { useRef, useState } from "react";
import classes from "./App.module.scss";
export default function App() {
const componetRef = useRef(null);
const [contentValue, setContentValue] = useState([]);
const addElement = () => {
const content = "this is para";
const type = componetRef.current.dataset.type || "p";
const classNames = componetRef.current.className;
const elemnt = React.createElement(type, { key: Date.now() }, content);
setContentValue([
...contentValue, // If you dont want to make it multiple times. just remove it
elemnt
]);
};
return (
<div className="App">
<button onClick={addElement}>Click here</button>
<div data-type="h1" ref={componetRef} className={classes.tag1}>
{contentValue}
</div>
</div>
);
}
Approach 2
import React, { useState } from "react";
import classes from "./App.module.scss";
const NewComponent = ({ classNames, content }) => {
return (
<div className={classNames} dangerouslySetInnerHTML={{ __html: content }} />
);
};
export default function App() {
// const classRef = useRef(null);
const [multiple, setMultiple] = useState([]);
const addElement = (e) => {
const classNames = e.target.dataset.class;
const content = e.target.dataset.content;
setMultiple([
...multiple, // If you dont want to make it multiple times. just remove it
<NewComponent
key={Date.now()}
classNames={classNames}
content={content}
/>
]);
};
return (
<div className="App">
<button
onClick={addElement}
data-class={classes.tag1}
data-content={"<p>asdasd</p>"}
>
Click here
</button>
{multiple}
</div>
);
}
Let me know if you have more question.
Here is sandbox

Related

how can create new array in main array in react js ,javascript

In that image i can explain what is my question
import './App.css';
import { useState } from 'react'
function App() {
const [head,setHead] = useState([])
const [tail,setTail] = useState([])
const main = [];
main.push(head,tail)
console.log(main);
const handleHead = () =>{
const HeadButton = 'H'
setHead([...head,HeadButton])
}
const handleTail = () =>{
const TailButton = 'T'
setTail([...tail,TailButton])
}
return (
<div className="App">`your text`
<button onClick={(e)=>handleHead(e)} >Head</button>
<button onClick={(e)=>handleTail(e)}>Tail</button>
<h1>{head.join(',')}</h1>
<h1>{tail.join(',')}</h1>
</div>
);
}
export default App;
i can 2 array inside of main array than how can create a third array inside of main array in react js
try this
// Get a hook function
const {useState} = React;
const Example = ({title}) => {
const [FinalList, setFinalList] = useState([]);
const [ConsecutiveHead, setConsecutiveHead] = useState(false);
const [ConsecutiveTail, setConsecutiveTail] = useState(false);
const handleHead = () =>{
if(ConsecutiveHead) {
const list = [...FinalList];
list[list.length -1].push("head");
setFinalList(list);
} else {
setFinalList(prev => [...prev, ["head"]]);
}
setConsecutiveHead(true);
setConsecutiveTail(false);
}
const handleTail = () =>{
if(ConsecutiveTail) {
const list = [...FinalList];
list[list.length -1].push("tail");
setFinalList(list);
} else {
setFinalList(prev => [...prev, ["tail"]]);
}
setConsecutiveHead(false);
setConsecutiveTail(true);
}
console.log(FinalList)
return (
<div className="App">
<button onClick={(e)=>handleHead(e)} >Head</button>
<button onClick={(e)=>handleTail(e)}>Tail</button>
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Example title="Example using Hooks:" />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

How to print a variable in html tag

Why variable a is undefined?
export default function Surah() {
let a;
const toDo= (id) => {
a = id;
console.log(a);
};
return (
<div>
<div>
<button onClick={() => toDo(1)}></button>
<div>{a}</div>
</div>
</div>
)
}
Can you explain what is wrong with my code ?
this is not an optimal way of using the variables. Instead we should useState hook. I'm attaching the code snippet below for your reference.
import {useState} from "react";
export default function Surah() {
const [a,setA] = useState(0); // Initialize it with a number
const Tafsir = (id) => {
setA(id);
};
return (
<div>
<div>
<button onClick={() => {
Tafsir(1);
console.log(a);
}}>Click Here</button>
<div>{a}</div>
</div>
</div>
)
}
you need to use a as state variable.
changing the variable value doesn't trigger the component to render again with the updated value, for this updated value you need to render the component again using setState.
import {useState} from "react";
export default function Surah() {
const [a, setA] = useState();
const toDo= (id) => {
setA(id);
};
return (
<div>
<div>
<button onClick={() => toDo(1)}>Click here</button>
<div>{a}</div>
</div>
</div>
)
}

How to set a JSX element to a variable without return in ReactJS?

I'm trying to assign a variable which will be a JSX element in ReactJS.
I want to do it like that:
const [useResultText, setResultText] = useState('');
const changeState = () => {
const br = <br />
setResultText('Hello' + br + 'world');
}
return (
<div onClick={changeState}>{useResultText}</div>
);
Is there any way to do it?
This works fine, as JSX just represents certain kinds of JavaScript objects. But you have to define it properly:
const [useResultText, setResultText] = useState('');
const changeState = () => {
const br = <br />
setResultText(<React.Fragment>Hello{br}world</React.Fragment>);
}
return (
<div onClick={changeState}>{useResultText}</div>
);
You might prefer something like a p or span tag over the fragment, depending on exactly what you want.
You're almost there. Just set your state to an element:
import React from "react";
import "./styles.css";
export default function App() {
const Elem = () => <div>Some stuff</div>;
const [useResultText, setResultText] = React.useState(Elem);
const changeState = () => {
const br = <br />;
setResultText(<div>Hello {br} World</div>);
};
return (
<div className="App">
<div onClick={changeState}>{useResultText}</div>
</div>
);
}
CS: https://codesandbox.io/s/vibrant-wind-0il8p?file=/src/App.js

How to append html video tag to a div in React

import React,{useRef} from "react"
const FuncComp = () => {
const videoItems = useRef();
const addVideo (stream){
videoItems.current.append(<video src = {stream}> </video>);
};
return (
<div ref = {videoItems}>
</div>
)
}
But addVideo function is not working as i can not append video tag to the div. is there another way to achive this?
you can write your code like this:
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
const MyComponent = () => {
const [videos, setVideos] = useState([]);
const addVideo = (id, stream) => {
const videosTemp = [...videos];
videosTemp.push({ id, stream });
setVideos(videosTemp);
};
const onAddVideoClick = () => {
const id = uuidv4();
const stream = "https://www.youtube.com/watch?v=haMOUb3KVSo";
addVideo(id, stream);
};
return (
<div>
<button onClick={onAddVideoClick}>Add Video</button>
{videos.map((video) => {
<video key={video.id} src={video.src} />;
})}
</div>
);
};

Get the ref of a functional component dynamically - ReactJS

I need to access my ref with a string variable that passed from props and contains the ref name that I want to get. something like this:
function MyComponent(props) {
const myFirstRef = useRef();
const mySecondRef = useRef();
const myThirdRef = useRef();
function handleClick() {
const targetRef = props.targetRef;
// The `targetRef` is a string that contains
// the name of the one of the above refs!
// I need to get my ref by string
// ...
}
return (
<div ref={myFirstRef}>
<div ref={mySecondRef}>
<div ref={myThirdRef}>
<button onClick={handleClick}>Find Ref and Do Something</button>
</div>
</div>
</div>
)
}
The targetRef is a string that contains the name of the above refs!
In class components there is this.refs and I could do what I want easily.
You may want to use a dictionary as object for mapping given key targetRef to a specific reference:
const ref = useRef({ first: undefined, second: undefined, third: undefined });
ref.current[targetRef];
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
const RefContainer = ({ targetRef }) => {
const ref = useRef({ first: undefined, second: undefined, third: undefined });
const handleClick = () => {
const coolRef = ref.current[targetRef];
console.log(coolRef);
};
return (
<div ref={node => (ref.current.first = node)}>
<div ref={node => (ref.current.second = node)}>
<div ref={node => (ref.current.third = node)}>
<button onClick={handleClick}>Find Ref and Do Something</button>
</div>
</div>
</div>
);
};
const App = () => {
return <RefContainer targetRef="third" />;
};
ReactDOM.render(<App />, document.getElementById('root'));

Categories

Resources