Reputation: 392
I am working on a React project, in that I have a button when I click the button then I have to apply margin-bottom: 100px. I am trying to achieve this but it is showing some error so help me to solve this error.
This is my code
import React, { useState } from 'react';
import './App.css';
const App = () => {
const [style, setStyle] = useState(null)
const applyStyles = () => {
style={
marginBottom: '100px'
}
}
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='first'>
<button onClick={applyStyles} className='btn btn-primary'>Click here</button>
</div>
<div className='second'>
<div className='box'></div>
</div>
</div>
</div>
</div>
)
}
export default App
Upvotes: 0
Views: 1022
Reputation: 353
Your approach does not match with react behavior. Just do like this. Have two css classes
.btn-clicked {
margin-bottom: '100px'
}
In the JSX
import React, { useState } from 'react';
import './App.css';
const App = () => {
const [style, setStyle] = useState(null)
const [clicked, setClicked] = useState(false)
const applyStyles = () => {
style={
marginBottom: '100px'
}
}
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='first'>
<button onClick={() => setClicked(true)} className={`btn btn-primary ${clicked ? 'btn-clicked': ''}`}>Click here</button>
</div>
<div className='second'>
<div className='box'></div>
</div>
</div>
</div>
</div>
)
}
export default App
Upvotes: 0
Reputation: 585
const App = () => {
const [style, setStyle] = useState(null)
const applyStyles = () => {
setStyle({
marginBottom: '100px'
});
}
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='first'>
<button onClick={applyStyles} style={style} className='btn btn-primary'>Click here</button>
</div>
<div className='second'>
<div className='box'></div>
</div>
</div>
</div>
</div>
)
}
It is not the best practice though. You should look at higher order components like withStyles.
Upvotes: 1