skip to Main Content

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.

2

Answers


  1. 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! 🙂

    Login or Signup to reply.
  2. hm I think your syntax is causing errors, it’s not quite React :). for instance, the component comes with these props (customImg, btnText), you will need to pass them when declaring the component in App.js.

    function App() {
          return (
            <div>
              <ImgBtn customImg={practRange} btnText="test" />
            </div>
          );
    }
    

    perhaps you’d be interested in reading up on React basics.

    https://reactjs.org/tutorial/tutorial.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search