I'm trying to iterate over an array in a custom hook in order to use an img, however the img doesn't display.
What am I doing wrong as I don't want to manually create a img tag in order to display all images.
import useData from "../useData";
// import unwind from '../img/unwind-portfolio-img.png'
function Work() {
const {projects} = useData();
return (
<section id="work">
{projects && (
<>
<img src={require(`${projects[0].img}`)} alt="" />
</>
)}
</section>
);
}
export default Work;
CUSTOME HOOK:
import unwind from './img/unwind-portfolio-img.png'
function useData() {
const projects = [
{
site_name: 'Unwind',
summary: 'An ecommerce book store built with React & Tailwind. View books, read their synopsis, and even add to your basket.',
img: '../img/unwind-portfolio-img.png',
// img: unwind,
link: 'https://nmukassa1.github.io/unwind'
}
]
return { projects };
}
export default useData;
CodePudding user response:
That is because you don't return a state from your custom hook. Custom hooks should be composed of one or more hooks.
Update your useData
hook like below:
const initialProjects = [
{
site_name: "Unwind",
summary:
"An ecommerce book store built with React & Tailwind. View books, read their synopsis, and even add to your basket.",
img: "../img/unwind-portfolio-img.png",
link: "https://nmukassa1.github.io/unwind"
}
];
function useData() {
const [projects, setProjects] = React.useState(initialProjects);
return { projects };
}
function Work() {
const { projects } = useData();
return (
<section id="work">
{projects && (
<div>
<h3>{projects[0].site_name}</h3>
<div>{projects[0].summary}</div>
<img src={`url(${projects[0].img})`} alt="" />
</div>
)}
</section>
);
}
ReactDOM.render(<Work />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
CodePudding user response:
I think the issue comes from the require
that you used to load the image. It won't work with a variable, it needs a static url to work.
However, you should be able to use this instead:
<img src={projects[0].img} alt="" />
Don't forget to make sure that the image is available at this path and that the file is included when you will build and deploy your application.