I'm a beginner with react and I have this code:
import {NavLink as Link} from 'react-router-dom'
return (
<div>
{posts.map((actualData, index) => (
<Link to={'/' + actualData.id}>
<div className='format_link'>
<div className='image_link'>
<div className='image'>
<img
className='images'
id={actualData.id}
src={getImage(actualData.path, 0)}
alt='Italian Trulli'
/>
<button
className='arrow right'
id={'button' + actualData.id}
onClick={() => changeImageNext(actualData.id, actualData.path)}>
{'>'}
</button>
<button
className='arrow left'
id={'button' + actualData.id}
onClick={() => changeImagePre(actualData.id, actualData.path)}>
{'<'}
</button>
</div>
</div>
<div className='desc_link'>
<div className='event'>
<div className='save'> </div>
</div>
</div>
</div>
</Link>
))}
</div>
)
I would like to use the buttons but if I pressed them I would be sent to the article link. Furthermore, I tried to replace buttons with Button by→import { Button } from 'semantic-ui-react'
Or to use event.stopPropagation()
(although maybe I didn't use it correctly), I used it like this:
function changeImagePre(e, id, images) {
e.stopPropagation()
var num = parseInt(result[id].images)
//...
}
return (
<div>
{posts.map((actualData, index) => (
<Link to={'/' + actualData.id}>
<div className='format_link'>
<div className='image_link'>
<div className='image'>
<img
className='images'
id={actualData.id}
src={getImage(actualData.path, 0)}
alt='Italian Trulli'
/>
<button
className='arrow right'
id={'button' + actualData.id}
onClick={(e) =>
changeImageNext(actualData.id, actualData.path)
}>
{'>'}
</button>
<button
className='arrow left'
id={'button' + actualData.id}
onClick={(e) => changeImagePre(actualData.id, actualData.path)}>
{'<'}
</button>
</div>
</div>
<div className='desc_link'>
<div className='event'>
<div className='save'> </div>
</div>
</div>
</div>
</Link>
))}
</div>
)
Therefore, to use the buttons in the Link how could I do? :(
Always prefer atomic design to avoid duplicating your code. First, write a separate component.
export default function Btn(props) {
return (
<button
type="button"
onClick={() => window.open(`${props.link}`)}>
{props.text}
</button>
)
}
Then, in your code, you merely need to import it and use it as follows:
import Btn from '@/components/global/atoms/Btn'
{/* Here goes the rest of your code */}
<Btn
link="https://www.mywebsite.com"
text="Button Text"
></Btn>