Answer the question
In order to leave comments, you need to log in
How to pass a DOM element to a parent component on a button click?
Good day to all!
I have a table with elements(
const [title, setTitle] = useState('');
<------------------------------------------ ------------>
const handleSubmit = (e) => {
e.preventDefault();
addSong(title);
setTitle('');
};
<table className="table table-bordered">
<TableHeader headers={headers} />
<tbody>
{commentsData.map((comment) => (
<tr key={comment.id}>
<th scope="row">{comment.id}</th>
<th className="col-sm-2">{comment.name}</th>
<th className="col-sm-3">{comment.email}</th>
<th className="d-flex align-middle justify-content-center">
<form onSubmit={handleSubmit}>
<fieldset>
<input
type="text"
className="form-control mr-sm-8 mb-4"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<button
className="btn btn-info col-sm-12"
onClick={handleClose}
>
Seleziona quantità
</button>
</fieldset>
</form>
</th>
</tr>
))}
</tbody>
</table>
function App() {
const addSong = (title) => {
// @ts-ignore
setSongs([{ title }]);
};
const [songs, setSongs] = useState([]);
return (
<div className="container">
<Modale addSong={addSong} />
<div className="song-list">
<table>
{songs.map((song, index) => {
return (
<tr key={index}>
<td>{song.title}</td>
</tr>
);
})}
</table>
</div>
</div>
);
}
export default App;
Answer the question
In order to leave comments, you need to log in
import { useRef } from "react";
const Item = ({ element, renderIn }) => {
const node = useRef(null);
const chooseThis = (event) => {
renderIn.current.appendChild(node.current);
};
return (
<li onClick={chooseThis}>
<h1 ref={node}>{element}</h1>
</li>
);
};
const List = ({ elements, renderIn }) => (
<ul>
{elements.map((element) => (
<Item element={element} renderIn={renderIn} />
))}
</ul>
);
const App = () => {
const elements = ["one", "two", "three"];
const renderIn = useRef(null);
return (
<>
<h1>
Chosen one: <div style={{ color: "red" }} ref={renderIn}></div>
</h1>
<List elements={elements} renderIn={renderIn} />
</>
);
};
export default App;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question