I am trying to remove an element when i click on the x button. Below is my code
const onRemoveItem = (el) => {
var element = el;
if (element != null) {
element.remove();
}
// chartInstance.resize();
};
const removeStyle = {
position: "absolute",
left: "11px",
top: 0,
cursor: "pointer"
};
return (
<ResponsiveGridLayout layouts={layout}>
<div key="1">
<NewvsReturnVisitors />
<span className="remove" style={removeStyle} onClick={onRemoveItem}>
x
</span>
</div>
<div key="2">
<NewvsReturnVisitors />
<span className="remove" style={removeStyle} onClick={onRemoveItem}>
x
</span>
</div>
<div key="3">
<NewvsReturnVisitors />
<span className="remove" style={removeStyle} onClick={onRemoveItem}>
x
</span>
</div>
</ResponsiveGridLayout>
);
but it keep returning me remove is not a function, is there a way in react to remove an element like how it will work in html?
This is my codesandbox link
You can maintain an array of displayed items. If the id of a div is in the array just add a class to hide it.
const { useState } = React;
function Example() {
const [ hidden, setHidden ] = useState([]);
// When you click on the X get the
// id of the closest div, and add it to state
function handleClick(e) {
const div = e.target.closest('div');
const { id } = div.dataset;
const newState = [...hidden, Number(id)];
setHidden(newState);
}
// Small function that each div calls
// to determine if the hidden class
// should be applied
function isHidden(id) {
return hidden.includes(id) && 'hidden';
}
return (
<div onClick={handleClick}>
<div className={isHidden(1)} data-id="1">
One
<span class="remove">x</span>
</div>
<div className={isHidden(2)} data-id="2">
Two
<span class="remove">x</span>
</div>
<div className={isHidden(3)} data-id="3">
Three
<span class="remove">x</span>
</div>
</div>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
span { cursor: pointer; color: red; }
.hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>