I'm trying to add an extra className for my <Button /> component but it's not adding the new className.
I have the Button component that contains
import React from 'react';
import './Button.css';
import { Link } from 'react-router-dom';
export const Button = ({ children, type, onClick }) => {
return (
<Link to="/" className="btn-mobile">
<button className={`btn`} onClick={onclick} type={type}>
{children}
</button>
</Link>
)
}
I'm calling <Button /> from another file and trying to add an extra className to that button but that's not working.
<div className="ticket">
<Button className="ticket"> Visit Now</Button>
</div>
When I checked the Developer Tools Elements, the Visit Now button only has the className of btn.
How can I add an extra className in this instance?
Button.js should be like this.
const Button = ({ className, onClick, type, children }) => (
<button className= {className} onClick={onClick} type={type}>{children}</button>
);
You can make it simple as follows.
const Button = props => <button {...props} />;
Then export the Button as default.
export default Button;
Create a variable using both the default button class, and the classname passed down in props in a template string, and then use that variable as the className.
Here's a full working example.
function Button(props) {
const {
classname,
handleClick,
type,
children
} = props;
const classnames = `btn ${classname}`;
return (
<button
className={classnames}
onClick={handleClick}
type={type}
>{children}
</button>
);
}
function Example() {
function handleClick(e) {
console.log(e.target.textContent);
}
return (
<div>
<Button
classname="ticket"
type="button"
handleClick={handleClick}
>Click me</Button>
</div>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
.btn { border: 2px solid red; }
.ticket { background-color: #55dd44; }
.ticket:hover { background-color: #ff3377; border: 1px solid blue; cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
In your Button.js class, you have to assign an external class that you provided from another component as a prop.
In your Button.js class, you have to update your code just like below
if functional component
<button className= {`btn ${props.className}`} onClick = {onclick} type = {type}> {children}/button>
Note:- make sure to use props as a parameter on functional component
if class-based component
<button className= {`btn ${this.props.className}`} onClick = {onclick} type = {type}> {children}/button>