Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  85] [ 3]  / answers: 1 / hits: 7388  / 4 Years ago, thu, june 11, 2020, 12:00:00

CONTEXT



I'm trying to dynamically add the React component into DIV/Another React component base on event f.g onClick event.



I tried and know I can add any HTML element into DIV by JS, simply by createElement and append into the DIV. But I want to add the react component into DIV.



Problem:



When I append React component into DIV, It will add [object Object], I am looking for a way to be able to render and insert React Components into DIV.



Here is codeSandBox : https://codesandbox.io/s/frosty-bouman-f95mx?file=/src/App.js



    import React from react;
import ./styles.css;
import Button from ./Button;

const addToCanvos = () => {
var canvos = document.querySelector(.canvos);
canvos.append(<Button />);
};

export default function App() {
return (
<div className=App>
<Button event={addToCanvos} />
<div className=canvos />
</div>
);
}

More From » reactjs

 Answers
6

Checkout this implementation. Basically you need to use the useState React Hook to store all the components that you want to add as children of the canvas.



export default function App() {
const [buttonsOnCanvos, setButtonsOnCanvos] = useState([]);
return (
<div className=App>
<Button
event={() => {
setButtonsOnCanvos([...buttonsOnCanvos, <Button />]);
}}
/>
<div className=canvos>{buttonsOnCanvos}</div>
</div>
);
}

[#3506] Tuesday, June 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
manuel questions
Sat, Mar 28, 20, 00:00, 4 Years ago
Fri, Jan 17, 20, 00:00, 4 Years ago
Sun, Jun 30, 19, 00:00, 5 Years ago
Sat, Jun 15, 19, 00:00, 5 Years ago
Sat, Feb 9, 19, 00:00, 5 Years ago
;