I would like to change the background image depending on the view file/URL. I don't quite know how to do this, I have 3 different images and 3 different views of Mindhunter, Sherlock etc. On "/mindhunter" there should be a mindhunter banner and on "/sherlock" a sherlock banner Background.js
import React from 'react';
import sherlockBaner from 'assets/SherlockBaner.svg';
const Background = () => {
return (
<>
<div>
<img className="baner" src={sherlockBaner} alt="baner" />
</div>
</>
);
};
export default Background;
Mindhunter.js
import React from 'react';
import Background from 'components/Series/Background/Background';
const Mindhunter = () => {
return (
<>
<Background />
</>
);
};
export default Mindhunter;
CodePudding user response:
Depending on how dynamic you want to make this you have two options:
Passing the "src" as a property to Background, and using props.src to set your img src
Using the path in your router to determine which url you have (take a look at react-router and query params) and then pass that into your component, which will then use some switch to select the correct background.
Let me know if you want more information on 1 or 2.
CodePudding user response:
I came up with something like this, it could probably be improved somehow
import React from 'react';
import mindHunterBaner from 'assets/MindhunterBaner.svg';
import sherlockBaner from 'assets/SherlockBaner.svg';
import breakingBadBaner from 'assets/BreakingBadBaner.svg';
import { useLocation } from 'react-router-dom';
const Background = () => {
const Location = useLocation();
let Baner;
if (Location.pathname == '/mindhunter') {
Baner = mindHunterBaner;
} else if (Location.pathname == '/sherlock') {
Baner = sherlockBaner;
} else if (Location.pathname == '/breakingbad') {
Baner = breakingBadBaner;
}
return (
<>
<div>
<img className="baner" src={Baner} alt="baner" />
</div>
</>
);
};
export default Background;