DOM remove method in react js
You should likely use a ref:
https://reactjs.org/docs/refs-and-the-dom.html
So you attach the ref to the DOM element, then you can imperatively remove that element just like you specified.
So in the component function body:
const myRef = useRef();
Then in the component render:
<Component ref={myRef} />
Then you can use the code in your question to remove the element from the DOM.
ref.remove();
If you need to do it when the page loads look at using useEffect to achieve this. Although if you're removing an element on page load, I question why you even need the element there in the first place ;).
Remove DOM in react.js,
Check the fiddle:
https://jsfiddle.net/zp5oqnsh/1/
const RenderItem = (props) => {
return(
<ul id="todo">
{props.items.map((item,i) =>
<li className='list-group-item' data-id={item.id} key={i}>{item.name}
<button className="btn btn-sm btn-primary" onClick={() => props.remove(item.id)}>X</button>
</li>
)}
</ul>
)
};
const TodoItems = React.createClass({
getInitialState() {
return {
items: [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
],
editing: false
}
},
edit(){
this.setState({editing: true})
},
save(){
this.setState({editing: false})
},
remove(id){
this.setState({
items: this.state.items.filter((el) => id !== el.id)
})
//return this.items.filter((item,i) => item.id !== id)
},
render(){
return(
<RenderItem items={this.state.items} remove={this.remove}/>
)
}
})
ReactDOM.render(
<TodoItems />,
document.getElementById('container')
);
Pass the remove()
as a props and call the remove()
onClick with the id and apply filter..
Hope it helps!
Add and Remove HTML Elements on Button Click in React
Here is a "React" way to do this, I'm not a React expert, so the code could be better, would accept corrections.
- Yes, react has more boilerplate codes, because you don't handle DOM directly and there is less "magic" which means you have more control overall. (specially as a controlled component)
- States should be as minimum as possible, you just have to hold the pure data, other decorative stuff let components to handle them.
- depends on the situation, you may want to separate the
Row
component into 2 separate components with more props. - ??? more suggestions?
UPDATE: after workin with React everyday for the last past 3 years, I found there are some bad practices on the previous code, I have update the code to be cleaner hopefully it helps you.
const Row = function(props){ const {checked, value, onChange, onChecked} = props; return ( <div> <input type="checkbox" checked={checked} onChange={onChecked} /> <input type ="text" value={value} onChange={onChange}/> </div> );}
class App extends React.Component { constructor(props){ super(props); this.state = { rows: [ {value: 'row1', checked: false}, {value: 'row2', checked: true}, {value: 'row3', checked: false}, ] }; } updateValue = (e, idx) => { const rows = [...this.state.rows]; // copy array because we don't want to mutate the previous one rows[idx].value = e.target.value; this.setState({ rows, }); } onChecked = (idx) => { const rows = [...this.state.rows]; // copy array because we don't want to mutate the previous one rows[idx].checked = !rows[idx].checked; this.setState({ rows, }); } addRow = () => { const rows = [...this.state.rows, {value:'', checked: false} ]; this.setState({ rows, }); } deleteRows = () => { this.setState({ rows: this.state.rows.filter(e => !e.checked) }); } render(){ return( <div> {this.state.rows.map((row, idx) => { return( <Row key={idx} value={row.value} checked={row.checked} onChange={(e) => this.updateValue(e, idx)} onChecked={() => this.onChecked(idx)} /> ) }) } <button onClick={this.addRow}> add </button> <button onClick={this.deleteRows}> delete </button> </div> ); }}
ReactDOM.render( <App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.development.js"></script>
<div id="app"> </div>
React: How can I remove a specific div element after clicking its associated button?
This is not prefered react way of doing things, but this will work:
import "./styles.css";
import { useState } from "react";
const App = () => {
const [counter, setCounter] = useState(1);
const handleAddDiv = () => {
setCounter(counter + 1);
};
const removeNode = (idx) => document.getElementById(`id-${idx}`).remove();
return (
<div className="App">
{Array.from(Array(counter)).map((item, idx) => (
<div key={idx} id={`id-${idx}`}>
<div>
<input type="text" />
<button onClick={() => removeNode(idx)}>Remove</button>
</div>
</div>
))}
<button onClick={handleAddDiv}>Add</button>
</div>
);
};
export default App;
Generaly if you would like to have it made correactly then you would want to map on a real array and have every item in array eighter having an unique id or simply use map index and then based on which item you click write a function to remove from that array our specific element.
Remove dynamic rendered element from dom in ReactJS
The problem is that in the first render you have {cards.length} calls to hook "useState" within GeraCard, but after deletion of one card, you will have {cards.length-1} calls to hook "useState". As the React docs state:
Don’t call Hooks inside loops, conditions, or nested functions.
Instead, always use Hooks at the top level of your React function. By
following this rule, you ensure that Hooks are called in the same
order each time a component renders. That’s what allows React to
correctly preserve the state of Hooks between multiple useState and
useEffect calls.
You should extract the content of map callback into separate a component.
const GeraCards = (cards, cart = false) => {
return cards.map((v, i) =>
<GeraCard card={v} index={i} cart={cart} />
);
};
const GeraCard = ({ card, index, cart }) => {
const [show, setShow] = useState(true);
const v = card;
return (
<div key={index}>
{show ?
<div className={styles.card}>
<div onClick={() => urlRender(v.url)} className={styles.cardContent}>
<div>
<span className={styles.cardTitulo}>{v.Nome}</span>
</div>
<div>
<span className={styles.cardData}>{v.Data}</span>
<span className={styles.cardAtivos}>{v.Ativos} ativo(s)</span>
</div>
{cart ? <div>R$ {FormatCapital(v.Capital)}</div> : null}
</div>
<span className={styles.trash}>
<FontAwesomeIcon
icon={faTrash}
color={"#3c3c3c77"}
onClick={(e) => {
setShow(false);
e.persist()
TrashHandler(v.Nome, e)
}}
/>
</span>
</div> :
null
}
</div>
);
}
React: remove element without id. useState/setState
The first job to delete an HTML element from the DOM is to find/get
that element. Then apply delete.
But, here you are having track on the divs in the state of the component. So, in nutshell, you have to have some keys that will uniquely point to that element in the state and DOM.
So, of course, your remove
method must do two job:
- Find the element from the DOM, it could be achieved by
e.target.parentNode
in your case and remove it by calling.remove
method on it. - Filter the
divs
object in yourstate
object so that thediv
can be erased
In case, you may have to perform 2 before 1.
Updated: Added a complete example about how to add and delete an element and keep track of them in state of the component
Codesandbox where I showed how you can delete and add element without modifying the HTML DOM. It's all about modifying the the React Virtual DOM (by updating state and hence re-rendering) that under the hood modifies the HTML DOM. Moreover, here the JSX for the elements (we are adding and deleting) is completely stored in the state which make it dynamically editable.
Removing a DOM element of a mounted Component
If you remove a DOM node that React rendered by directly manipulating the DOM, React will not know of these changes. If the React component is then re-rendered, the previously removed DOM node will reappear because it still exists in Reacts virtual DOM.
You should avoid manipulating the parts of the DOM which React has created. This may cause unwanted behavior in your application.
For example, removing a DOM node which React rendered may throw the following exception on re-render:
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
or some other DOMException.
Here's what the official documentation says about updating the DOM:
React is unaware of changes made to the DOM outside of React. It
determines updates based on its own internal representation, and if
the same DOM nodes are manipulated by another library, React gets
confused and has no way to recover.This does not mean it is impossible or even necessarily difficult to
combine React with other ways of affecting the DOM, you just have to
be mindful of what each are doing.The easiest way to avoid conflicts is to prevent the React component
from updating. You can do this by rendering elements that React has no
reason to update, like an empty<div />
.
It goes on with an example integration of React with jQuery, here.
Finally, I suggest further reading on the Virtual DOM. The official documentation doesn't seem to say much about it, but search online and you'll find a plethora of guides; like this one.
Can we remove an element from the DOM?
You are missing the point of React. You don't manually modify the element tree. You declaratively map properties/state to elements and let React do all of the modifications.
var App = React.createClass({
render: function() {
// Get the node from the passed-in props
var node = this.props.node;
// generate the child components
var components = node.map(function(props) {
return React.createElement('g', {
id: props.id,
key: props.id
},
React.createElement('path', props));
});
// render them in a div
return React.createElement('div', null, components);
}
});
// first time it will create the DOM
// after that it just modifies the DOM
function renderApp(node, element) {
ReactDOM.render(React.createElement(App, { node: node }), element);
}
// Call when you want to get rid of the App completely
// and cleanup memory without reloading the page
function destroyApp(element) {
ReactDOM.unmountComponentAtNode(element);
}
// Initial render
var node = Interfaces.Embroidery.node;
renderApp(node, document.getElementById('parentDrawingNode'));
function updateNodeOnSomeUserActionThatHappensOutsideOfReact(...) {
node.push(...); // or whatever modification you want
// re-render
renderApp(node, document.getElementById('parentDrawingNode'));
}
Read more about this style here: https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html
Note this is what you'd do if the "user actions" are occurring outside of your React components (i.e. elsewhere in the app). If the "user actions" occur as events within your React components, you'd only ever call render
once, and instead the App would hold the nodes as state
and would just call this.setState({ node: modifiedNodes });
to change the state, which would cause React to update your DOM.
Related Topics
Puppeteer Wait Until Page Is Completely Loaded
How to Redirect to Another Page in Reactjs When a If Condition Is Executed
Css Div Height Not Expanding to Fit Content or Wrapping Content
Get Array of Values from Multiple Inputs Using Jquery
How to Download a File With Node.Js (Without Using Third-Party Libraries)
Remove Time from Gmt Time Format
Bootstrap Button Drop-Down Inside Responsive Table Not Visible Because of Scroll
Filter Json Object to String Array by Key Value
Open a New Tab on Button Click in Angularjs
Eslint: Disable Warning - 'Defined But Never Used' for Specific Function
Jquery Do Not Allow Alphabets to Be Entered in Input Field
Make Redirect to New Url But Remove Previous from History
Using Scrollintoview With a Fixed Position Header
Regular Expression Which Allow Only Characters or Space
Converting Text to Unicode in JavaScript
How to Avoid the Setstate()/Render() Endless Loop When Passing Data from Child to Parent