is there any way to use reusable component with same button should perform different functionality

Viewed 30

I want to make one reusable component name: ABC 5 times in which all ABC component should have different data and i want to add a functionality where 1st and 5th ABC should have true state by default and the remaining 3 should have false and then i want to close and open particular component with an arrow but the problem is that all component are opening and closing instead of the particular one

1 Answers

because you should add functionality as a prop from the parent of the component you are using it in. as in

const CustomButton = ({handleClick, buttonText, otherProps}) => {

return <button onClick={handleClick}>{buttonText}</button>
}


const App = () => {
return (
  <div>
    <CustomButton buttonText={"SEND"} handleClick={() => {/*fetch something or do something*/}} />
    <CustomButton buttonText={"DELETE"} handleClick={() => {/*do another thing*/}} />
    <CustomButton buttonText={"DO SOMETHING"} handleClick={() => {/*say hi to your users*/}} />
    <CustomButton buttonText={"DO SOMETHING ELSE"} handleClick={() => {/*you can do anything*/}} />
  </div>
)

}

if you need to render buttons according to the data count(example: length of an array) you can use Array.map method to render components and use its index to open and close the elements by passing the index as a prop to CustomButton and using the handleClick function as () => {handleClick(index)} and handle the operation in just one function in the parent component.

Related