Search code examples
reactjsweb-component

Generalizing custom buttons in React: custom text and background-image


I am trying to create a group of four buttons. The buttons are almost identical save the background-image and the text on the button. I could create a component for each button, but am trying to implement a more generalized approach. My native language is Java, I keep trying to think of components as objects.

I tried

ImgBtn.js (This would act like the constructor)

import './App.css';
function ImgBtn(customImg, btnTxt) {
    return (
     <>
      <button style = {{backgroundImage : customImg}}>'btnTxt'</button>
     </>   
      );
  }

  export default ImgBtn;

**App.js ** (Where I would invoke the four instances of ImgBtn, just focusing on one for now)

import ImgBtn from './ImgBtn';
import practRange from "./btn_img/p-range.png";


function App() {
render(
    <div>
   { <ImgBtn(customImg: practRange, btnTxt: sample)/>;}
   </div>
);
}

export default App;

**App.css ** (The general styling for the buttons)

 body {
  background-color: aqua;
}
button {
  font-size: 1rem;
  border: none;
  background-color: white;
  font-family:Arial;
  font-weight:bold;
  height: 200px;
  width: 200px;
  border-radius: 4px;
}
img {
  margin-top: none;
  padding-top: none;

}

I was hoping ImgBtn would act as a "constructor" that I could use to invoke the four different buttons, but I got an error. I am pretty sure it all relates to my confusion around how parameters (props?) work in React.

Thank you.


Solution

  • The props comes as an object in the components. So you have to destructurine it in your component like this:

    function ImgBtn({customImg, btnTxt}) {
        return (
         <>
          <button style = {{backgroundImage : customImg}}>{btnTxt}</button>
         </>   
          );
      }
    

    And in your App.tsx, you pass the props directly in the component like this:

    function App() {
    render(
        <div>
         <ImgBtn customImg={practRange} btnTxt={'sample'})/>
       </div>
    );
    }
    

    To know more details about how the props works in React, take a look at the official docs.

    Hope this answer helped you! :)