Let's say I have a parent component like this:
export default class InputView extends Component {
constructor(props) {
super(props);
this.state = {
nr: [2, 3],
};
}
handleDel = () => {
console.log('klick');
};
render() {
const elements = this.state.nr.map(inputPdf(nr));
return (
<div>
{elements}
</div>
);
}
}
The function inputPdf() creates another component;
const inputPdf = (nr) => {
return (
<div class="card">
<button type="button" class="close" aria-label="Close" onClick={this.props.handleDel()}> </button>
</div>
);
};
And now I want to use the function handleDel() in my child component.
How to get this running...?
There are some issues in code. But if you want to go with your way. It should be like this:
import React from "react";
import "./style.css";
class InputView extends React.Component {
constructor(props) {
super(props);
this.state = {
nr: [2, 3],
};
}
handleDel = () => {
console.log('klick');
};
render() {
const elements = this.state.nr.map((data) => inputPdf(data,this.handleDel));
return (
<div>
{elements}
</div>
);
}
}
const inputPdf = (nr,onClick) => {
return (
<div class="card">
<button type="button" class="close" aria-label="Close" onClick={onClick}>
{nr} </button>
</div>
);
};
export default function App() {
return (
<div>
<InputView/>
<p>Start editing to see some magic happen :)</p>
</div>
);
}
Here is the demo: https://stackblitz.com/edit/react-txqp8k
Issue in code:
Better way:
return this.state.nr.map(data => <InputPdf onClick={this.handleDel} nr={nr}/>)
//where
const InputPdf = ({nr,onClick}) => {
return (
<div class="card">
<button type="button" class="close" aria-label="Close" onClick={onClick}>
{nr} </button>
</div>
);
}