Reputation: 2685
I am new to react js. Here I have following code where. ,
<Link to='/test/1'>
<div>
// Here I have my select component as well
</div>
</Link>
Now, When I am trying to select that element from the dropdown that time, not able to because it is getting navigated because of the Link
. So, How do I make that to select even if there is a link ,
and that select has to be in the Link tag as it is a wrapper for that div.
Upvotes: 1
Views: 166
Reputation: 6965
You can capture click events on the select and prevent their default action:
<Link to='/test/1'>
<div>
<select onClick={e => e.preventDefault()}>
<option>something</option>
</select>
</div>
</Link>
This prevents the click event from opening the link.
If you wanted to generalize this so that it works on a few different elements inside your Link, you could create a wrapper component:
export const PreventDefaultClick = ({children}) => {
return (
<div onClick={e => e.preventDefault()}>
{children}
</div>
)
}
You'd use it like this:
<Link to='/test/1'>
<div>
<PreventDefaultClick>
<select>
<option>something</option>
</select>
</PreventDefaultClick>
</div>
</Link>
Here's some working code:
const PreventDefaultClick = ({children}) => {
return (
<div onClick={e => e.preventDefault()}>
{children}
</div>
)
}
const App = () => {
return (
<a href='https://example.com'>
<PreventDefaultClick>
<select>
<option>one</option>
<option>two</option>
</select>
</PreventDefaultClick>
<p>clicking here will still open the link</p>
</a>
)
}
ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='app'>
</div>
Upvotes: 1