Hej,
As I'm beginner in React. I have a problem of displaying my image passed from state to component.
App.js
this.state = {
projects: [
title: 'xxx',
image: require(../src/img/landscape.jpg)
]
}
<Works projects={this.state.projects}/>
Work.jsx
{this.props.project.title}
{this.props.project.image}
Title is displaying without any problems but image doesnt appear. Do I need to bind it in another way???
First of all, the state must be written like this:
state = {
projects: [
{ title: 'xxx',
image: require("../src/img/landscape.jpg")
}
]
}
now the work.js will contain the following code:
<div>
{this.state.projects.map((item, index) => {
return (
<div key={index}>
<p>{item.title}</p>
<img src={item.image} />
</div>
)})
}
</div>
Is your state like that you gave in your question or is it like that?
state = {
projects: [
{
title: "xxx",
image: require( "../src/img/landscape.jpg" ),
},
],
}
With your code at least you should see the path of the image. But, if you want to see the image you need to use <img>.
<div>
{
props.projects.map( project => (
<div>
<p>{project.title}</p>
<img src={project.image} />
</div>
) )
}
</div>
Related
I'm running into an issue where I've created a non page component with a StaticQuery that is pulling information with a set up like this.
const BestSellers = () => (
<div>
<StaticQuery
query={bestSellerQuery}
render={data => (
<div>
{data.allMarkdownRemark.edges.map(({ node }) => (
<Card className="m-2 index-card" key={node.id}>
<Link to={node.fields.slug}>
<GatsbyImage
className="card-img-top"
image={node.frontmatter.image}
alt={node.frontmatter.description}
/>
</Link>
<hr />
<CardBody>
<Link to={node.fields.slug}>
<CardTitle className="h4 text-light text-wrap">
{node.frontmatter.title}
</CardTitle>
</Link>
<CardSubtitle>{node.frontmatter.description}</CardSubtitle>
{/* <CardSubtitle>{node.excerpt}</CardSubtitle> */}
<CardSubtitle className="float-left mt-5">
Price: ${node.frontmatter.price}
</CardSubtitle>
<CardSubtitle>
<Badge color="danger float-right mt-5">
{node.frontmatter.tag}
</Badge>
</CardSubtitle>
</CardBody>
</Card>
))}
</div>
)}
/>
</div>
);
const bestSellerQuery = graphql`
query bestSellerQuery {
allMarkdownRemark(
filter: { frontmatter: { tag: { eq: "popular" }}}
sort: { fields: [frontmatter___date], order: DESC }
limit: 2
) {
edges {
node {
id
frontmatter {
title
description
price
tag
image {
childImageSharp {
gatsbyImageData(
layout: CONSTRAINED
height: 600
placeholder: BLURRED
formats: [AUTO, JPG]
transformOptions: { fit: COVER, cropFocus: ATTENTION }
)
}
}
}
fields {
slug
}
excerpt
}
}
}
}
`
export default BestSellers;
What I'm doing is my pages are being created programmatically from a Markdown file once it is clicked on so I'm trying to import this into the template that i use to create pages and it just shows loading(static query) I've tried using this same query in pages that do and don't have a page query on them and it results in the same as using this in the template component that I'm trying to use it in.
It was the issues in the graphql query which was being used more specifically the line
filter: { frontmatter: { tag: { eq: "popular" }}}
the issue was the "popular" in the MD file is in caps so by changing it to "POPULAR" that solved it....
I am currently learning Alpine JS and trying to find examples of binding using x-ref ( As per to the Docs: https://github.com/alpinejs/alpine#x-ref )but there isn't many as it only became a feature late year year. I am just wondering could anyone provide an example on how to x-ref a variable so it can be used in a Fetch Method.
Currently I am not using x-ref and using x-html which is not rendering the HTML code for some reason, so I'm hoping by using x-ref it will work(?)
<div x-data="foo()" x-init="init()" >
<div>
<template x-for="foo in list" :key="foo.id">
<button
#click="activeTab = itemfooid"
x-text="foo.name"
x-ref="foo.name"
x-on:click="getHTML( item )"
>
</template>
<div x-ref="myxRef" x-show="activeTab === 0" x-html ="foo[0].name"> post </div>
</div>
Fetch Foo
function foo(){
activeTab: 0, // Set active tab to POST
list: [],
init(){
this.list = { id: 1, name: 'foo', code: 'null' },
}
}
getHTML( foo){
fetch('url/example.html')
.then(response => response.text() )
.then(html => {
if( foo.code=== undefined ){
foo.code= html
}
})
.catch( error => console.log ( error ) )
},
Example HTML:
<code language-php> $test = 1 <div x-if="country === undefined"> echo "Hey"; </div> return $test </code>
My code will only have the code brackets and the rest inside will be plain text.
Below is an example I found on which I'm trying to follow but that doesn't work either. https://laracasts.com/discuss/channels/javascript/laravel-alpinejs-fetch-and-x-ref
<div x-ref="test" class="window-content"></div>
<script>
function windowManager()
fetch('/frontend/blog')
.then(response => response.text())
.then(html => { this.$refs.test.innerHTML = html })
}
</script>
I'm building my website with GatsbyJS and graphsql. On my projects site I want to display a grid with Images that Link to further sites.
In order to do that I need to query multiple images. I created a folder in my images folder called "portfolio" and I want to query all the pictures in there.
I have used useStaticQuery before but I've read that currently it's only possible to query one instance so I tried doing it like this, but the code is not working. Any help? Thanks a lot!
import React from 'react'
import Img from 'gatsby-image'
import { graphql } from 'gatsby'
const Portfolio = ({data}) => (
<>
{data.allFile.edges.map(image => {
return (
<div className="sec">
<div className="portfolio">
<div className="containerp">
<Img className="centeredp" fluid={image.node.childImageSharp.fluid}/>
</div>
</div>
</div>
) })}
</>
)
export default Portfolio
export const portfolioQuery = graphql`
{
allFile(filter: {relativeDirectory: {eq: "portfolio"}}) {
edges {
node {
id
childImageSharp {
fluid(maxWidth: 500) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
Is it possible that you have some images missing, so none are rendering?
You could try checking that the image is present before rendering the Img, like this:
{image.node.childImageSharp &&
<Img className="centeredp" fluid={image.node.childImageSharp.fluid}/>}
NB:
If you like, you could also make it a bit clearer by assigning your mapping object (edges) to a variable. It doesn't make that much difference in this example but can be clearer if you have more going on in your component.
E.g.
const Portfolio = ({data}) => (
<>
const images = data.allFile.edges
{images.map(image => {
return (
<div className="sec">
<div className="portfolio">
<div className="containerp">
<Img className="centeredp" fluid={image.node.childImageSharp.fluid}/>
</div>
</div>
</div>
) })}
</>
)
It's most likely that you probably need to set up your 'gatsby-source-filesystem' to recognize images within a query.
in your gatsby-config.js:
{
resolve: gatsby-source-filesystem,
options: {
name: images,
path: ./src/images/,
},
},
I decided to create a small project in new technology and I choose Gatsby. To let you know I don't work with React and GraphQl before. So thanks to Gatsby I can see also other technologies. So, for now, I try to make an index survey page where the footer and header are modifiable. I take for my backend Contentful and I succeed to do the connection between the content from ContentFul and my component footer. But when I try to do a query in the page index.js impossible to get the data, but they exist (I checked on graphql).
I try to make the query in the component, make the query in a hook and then call the hook. But nothing changes always undefined
In my index.js:
const query = graphql`
query header{
contentfulHeader {
id
titleCard
descriptionCard
logoCard {
file {
url
}
}
}
}
`
const SurveyTitleCard = props => {
return (
<>
<div className="row">
<div className="survey-title card blue-grey darken-3 col s10 offset-s1 m6 offset-m3">
<div className="card-content grey-text text-lighten-3 center-align">
<div className="row logo valign-wrapper">
<div className="col s6 offset-s3 m4 offset-m4">
<img
className="responsive-img"
src=""
alt="logo company"
/>
</div>
</div>
<div className="card-title">
{query.contentfulHeader.titleCard}
</div>
<p>We would love to hear your anonymous thoughts and feedback</p>
</div>
</div>
</div>
</>
)
}
// INDEX PAGE
const IndexPage = () => (
<Layout>
<SEO title="Home" />
<SurveyTitleCard />
</Layout>
)
Here the data from GraphQl:
Here my gatsby-config.js:
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `#AntoineB`,
},
plugins: [
{
resolve: `gatsby-source-contentful`,
options:{
spaceId: `MY_SPACE_ID`,
accessToken: `MY_ACCESS_TOKEN`,
},
},
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
See the docs regarding querying data in components using StaticQuery
import React from "react"
import { StaticQuery, graphql } from "gatsby"
export default () => (
<StaticQuery
query={graphql`
query header{
contentfulHeader {
id
titleCard
descriptionCard
logoCard {
file {
url
}
}
}
}
`}
render={data => (
<>
<div className="row">
<div className="survey-title card blue-grey darken-3 col s10 offset-s1 m6 offset-m3">
<div className="card-content grey-text text-lighten-3 center-align">
<div className="row logo valign-wrapper">
<div className="col s6 offset-s3 m4 offset-m4">
<img
className="responsive-img"
src=""
alt="logo company"
/>
</div>
</div>
<div className="card-title">
{data.contentfulHeader.titleCard}
</div>
<p>We would love to hear your anonymous thoughts and feedback</p>
</div>
</div>
</div>
</>
)}
/>
)
I am trying to fetch results from database in News.vue, and display them in Topnews.vue. I have two links fetched. When I click link1, it shows up the Topnews.vue template with everything working as intended, however, if i click link2, nothing happens, except for that the URL changes, but the template does not show up the result. If i refresh the page and click link2 or click on the navbar, then link2, it shows up, and same, clicking then link1, changes the URL, but doesnt show up. I'm really stuck on that and I'd be really glad if you help me out on that issue. Hope you understand.
News.vue
<template id="news">
<div class="col-sm-5">
<div class="cars" v-for="row in filteredNews" >
<div class="name" >
<p class="desc_top_time">{{row.created_at}}</p>
<span class="last_p"> {{row.category}}</span>
<h3 style="margin-bottom:-4px; font-size: 16px;">
<router-link class="btn btn-primary" v-bind:to="{name: 'Topnews', params: {id: row.id} }">{{row.title}}</router-link></h3>
</div></div></div>
</template>
<script>
export default {
data: function() {
return {
news: [],
}
},
created: function() {
let uri = '/news';
Axios.get(uri).then((response) => {
this.news = response.data;
});
},
computed: {
filteredNews: function() {
if (this.news.length) {
return this.news;
}
}
}
}
</script>
Topnews.vue
<template id="topnews1">
<div class="col-sm-7">
<div class="cars">
<img :src="topnews.thumb" class="img-responsive" width=100%/>
<div class="name" ><h3>{{ topnews.title }}</h3>
<p>
<br>{{ topnews.info }}<br/>
</p>
</div></div></div>
</template>
<script>
export default {
data:function(){
return {topnews: {title: '', thumb: '', info: ''}}
},
created:function() {
let uri = '/news/'+this.$route.params.id;
Axios.get(uri).then((response) => {
this.topnews = response.data;
});
}
}
</script>
Like GoogleMac said Vue will reuse the same component whenever possible. Since the route for both IDs use the same component Vue will not recreate it, so the created() method is only being called on the first page. You'll need to use the routers beforeRouteUpdate to capture the route change and update the data.
in TopNews.vue:
export default {
data:function(){
return {topnews: {title: '', thumb: '', info: ''}}
},
beforeRouteEnter:function(to, from, next) {
let uri = '/news/'+ to.params.id;
Axios.get(uri).then((response) => {
next(vm => {
vm.setData(response.data)
})
});
},
beforeRouteUpdate: function(to, from, next) {
let uri = '/news/'+ to.params.id;
Axios.get(uri).then((response) => {
this.setData(response.data);
next();
});
},
methods: {
setData(data) {
this.topnews = data
}
}
}
If you click a link referring to the page you are on, nothing will change. Vue Router is smart enough to not make any changes.
My guess is that the IDs are messed up. If you are using Vue devtools you will be able to easily see what data is in each link. Are they as you expect.