Depending on a conditional stored in component state, I would like a particular component being rendered to either be wrapped in a Link tag or a regular div tag (or no tag works just as well!)
What I'm currently doing seems verbose and redudnant; I feel like there's a shorter way I could write this component to keep my code DRY.
Both variables storing my linkThumbnail and defaultThumbnnail components are pretty much exactly the same, except for the fact that one of them is contained within a Link component.
I then use a ternary operator in the return statement to give me the desired component.
Here's some pseudocode as an example:
import React, { Component } from "react";
import { Link } from "react-router-dom";
class ExampleComponent extends Component {
state = {
renderLink: false
};
render() {
const linkThumbnail = (
<Link
to={{
pathname: `/someMovieId`,
state: 'some-data'
}}
>
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
</Link>
);
const defaultThumbnail = (
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
);
//here I use a ternary operator to show the correct component...shorter method of doing this?
return this.state.renderLink ? linkThumbnail : defaultThumbnail;
}
}
export default ExampleComponent;