how can I add props inside class in html which already exists

Viewed 68

I want to add a class from another file as a prop, but I am not able to do it.

file 1

import React from 'react'
    
    const Button = (props) => {
        return (
            <div>
                <button class={"btn btn-primary" props.classes }   type="submit" >{props.name}</button>
            </div>
        )
    }
    
    export default Button

file 2:

<Button name="Sign Up" classes="me-sm-0"></Button>
2 Answers

You just have to pass the desired className in the props just like below:

 const Button = (props) => {
        return (
            <div>
                <button className={`btn btn-primary ${props.className}`}   type="submit" >{props.name}</button>
            </div>
        )
    }

And this will be the Component used:

<Button name="Sign Up" className="me-sm-0"></Button>

I have read your article carefully. I think your attempt to pass classes as props of the Button component worked really well. If there is one disappointment, the syntax of react jsx is wrong. In react jsx, the class property of html should be written as className. And use ...${regexp}, one of the new features in es6. I attach the code below.

--App.js

import React from 'react';
import './style.css';
import Button from './Button';
export default function App() {
  return (
    <div>
      <Button name="Sign Up" classes="me-sm-0" />
    </div>
  );
}

--Button.js

import React from 'react';
export default function Button(props) {
  return (
    <div>
      <button className={`btn btn-primary ${props.classes}`} type="submit">
        {props.name}
      </button>
    </div>
  );
}
Related