Having trouble using Create React App to change a background image I feed to my component through props. The docs say use the import syntax. This works but it would mean I have to hard code every background image to each component. Anyway to do this dynamically?
I noticed it won't let me use template literals on the import syntax as well. That would have fixed my issue I think.
import '../css/Avatar.css';
import photo from "../images/joe_exotic.jpg";
const Avatar = (props) => {
return (
<div
style={{backgroundImage: `url("${photo}")`}}
className="avatar">
</div>
)
}
export default Avatar;
P.S: I checked out the other articles on StackOverflow regarding this and they didn't provide much help.
If you wanna avoid this way of doing, you can put your images in the public folder of your React app, et grab them like so :
import '../css/Avatar.css';
const Avatar = (props) => {
return (
<div
style={{backgroundImage: `url("/joe_exotic.jpg")`}}
className="avatar">
</div>
)
}
export default Avatar;
I hope it works for you. good luck.
import '../css/Avatar.css';
import photo from "../images/joe_exotic.jpg";
const Avatar = (props) => {
return (
<div
style={{backgroundImage:url(photo)}}
className="avatar">
</div>
) }
export default Avatar;
Related
I am running into a slight problem when trying to render a React Bootstrap Icon in Next.js.
I am using getStaticProps to make a call to the Notion API, to then use as props in my page, and everything is working fine.
However, I would like to define which icon to use in the Notion CMS.
According to the React Bootstrap Icons package on NPM you can do it this way, however I am not using TypeScript so I edited the code slightly (further below):
Icons.js
import * as icons from 'react-bootstrap-icons';
export const Icon = ({ iconName, ...props }) => {
const BootstrapIcon = icons[iconName];
return <BootstrapIcon {...props} />;
}
Services.js
import React from 'react';
import Card from 'react-bootstrap/Card';
import CardGroup from 'react-bootstrap/CardGroup';
import { Icon } from '../icons';
function Services({data}) {
const renderItems = data?.map((record) => {
// saving notion data as variables
let icon = record.properties.Icon.title[0].text.content
let title = record.properties.Service.rich_text[0].plain_text
let description = record.properties.Descrip.rich_text[0].text.content
return <Card key={record.id}>
<Icon
iconName={icon}
color="#96DBAE"
size={96}
/>
<Card.Body>
<Card.Title>{title}</Card.Title>
<Card.Text>{description}</Card.Text>
</Card.Body>
</Card>
})
return (
<>
<section >
<CardGroup>
{renderItems}
</CardGroup>
</section>
</>
);
}
export default Services;
I am running into this error. When I console.log(icon) it displays as a string, however when I pass the variable as a prop on the Icon, the error shows. If I type a regular string e.g iconName={"Globe"} everything works fine.
Any ideas how to solve this or where I might be going wrong? Any help is massively appreciated!
I'm trying to use react icons without import the icon of the lib. Is it possible to call the icon and pass the name like <Icon name="FiMenu" /> or <Icon name="FiArrowRight" />?
Nothing happened, looks like property Icon does not exists from react-icons.
The not best practice, but you can also create oan object with key (name of icon) and value the icon. So after this import of your icons.
Example:
import {FaBeer} from "react-icons/fa"
const icons = {
"FaBeer": FaBeer
}
export const Icon ({name, ...props} ) => {
const IconComponent = icons[name]
return <IconComponent {...props} />
}
There is no such component called Icon in the library or in React so you do need to individually import the components.
Follow the documentation: https://github.com/react-icons/react-icons
The basic usage is:
import { FaBeer } from 'react-icons/fa';
class Question extends React.Component {
render() {
return <h3> Lets go for a <FaBeer />? </h3>
}
}
If you really want to understand what is happening I suggest having a look through the source code.
I am a new react-js learner and I am having a hard time adding css to my classes that I have inside my react component.
Here is the current code:
import React from 'react';
const Home = () => {
return (
<>
<div class="container">
<h1 class="mainHeader">Home</h1>
<h2>helloo</h2>
</div>
</>
);
};
.container {
// CSS would go here
}
export default Home;
In just HTML and CSS, I was able to apply css on the container div class by just using '.' and whatever the class name was. However, this is giving me an error.
Put the css in its own file, with a .css extension, then import it. Assuming you used create-react-app to set up your project, it will already have appropriate configuration for importing css files. Additionally, you need to use className for the prop, not class
// In a new file home.css:
.container {
// css goes here
}
// In the file you've shown:
import React from 'react';
import './home.css';
const Home = () => {
return (
<>
<div className="container">
<h1 className="mainHeader">Home</h1>
<h2>helloo</h2>
</div>
</>
);
};
export default Home;
Or you can declare it in json format or like you would an object, not in CSS form. Treat it as you are writing in js, which you actually are. See the edit below:
import React from 'react';
const Home = () => {
return (
<>
<div style={container}>
<h1 className="mainHeader">Home</h1>
<h2>helloo</h2>
</div>
</>
);
};
const container = {
// CSS would go here
color: 'red',
background: 'blue'
}
export default Home;
I am new to react and there is this challenge that i am having,
I have slider created a component
import React from 'react'
import NextEvent from '../nextEvent/NextEvent'
import './slider.css';
function Slider(props) {
const {id, image, sub_title, title} = props;
return (
<main id='slider'>
<div className="slide" key= {id}>
<div className="slide-image">
<img src={image} alt="slider-background"/>
</div>
<h1>{title} </h1>
<h5>...{sub_title}</h5>
</div>
<div className="event-countdown">
<NextEvent/>
</div>
</main>
)
}
export default Slider
I need to have this banner component on almost all my pages, and on each of the pages, it comes with a
different information (image, title, subtitle)
the backend guy sent the api and i consumed, but the problem is that, if i consume the api on the
component directly, all the pages will have the same info on the banner component which is not what i want,
also consuming the API on the homepage seemed like it was not the right thing to do, so i created another component which
collects the Api and i then added that new component to my homepage.
now my question goes:
did i do the correct thing ?
if correct, does it mean i have to create new corresponding components that will receive the APi for
each page i want to display the banner just like i did for the homepage?
will i have to as the backend guy to create different apis for each of the pages in which the
component is to be displayed
if no please help me with an efficient way which i can inject data coming from the backend into a
component which will be displayed on different pages with different data
this is the new component i created for the APi consumption
import React, {useState, useEffect } from 'react'
import NextEvent from '../../components/nextEvent/NextEvent'
import axios from "axios";
import '../../components/slider/slider.css';
const sliderUrl = "*************************************"
function HomeSlider(props) {
const [sliderData, setSliderData] = useState([]);
const { image, sub_title, title} = props;
const getSliderContents = async () => {
const response = await axios.get(sliderUrl);
const content = response.data;
setSliderData(content);
}
useEffect(() => {
getSliderContents();
}, [])
// console.log("slider", sliderData)
if(sliderData) {
return (
<main id='slider'>
{sliderData.map((item) => {
return (
<div className="slide" key= {item.id}>
<div className="slide-image">
<img src={item.image} alt="slider-background"/>
</div>
<h1>{item.title} </h1>
<h5>...{item.sub_title}</h5>
</div>
)
})}
<div className="event-countdown">
<NextEvent/>
</div>
</main>
)
}
}
export default HomeSlider
this is the Homepage i displayed it
function HomePage() {
return (
<div>
<NavBar/>
<SecondaryMenu/>
<HomeSlider />
<FeaturedBox />
Please any help is appreciated, i have search all over but no one explains how to display
component with different data on different pages
So i just wanted to get back on this, i figured i have to setup a service point where i call the api and then consume the endpoints on each page as desired
I'm having some difficulty trying to insert dynamic images into "cards" that I want to render. I'm loading the necessary information for the components from Firebase-database (including the relative path to the image) and, during the callback function, pushing each created component into an array that I'm rendering to the page.
The issue is that <img src={fly.image)/> doesn't work, despite the correct path being loaded in (I've checked) and the images appropriately imported. Here's the code:
import React, { Component } from 'react';
import * as firebase from 'firebase';
import './Flies.css'
import Adams from './images/adams.jpg'
import Bugger from './images/bugger.jpg'
import Caddis from './images/caddis.jpg'
import Hendrickson from './images/hendrickson.jpg'
class Flies extends Component {
constructor(props){
super(props);
this.state = {
flies: []
}
}
componentDidMount(){
var allFlies = firebase.database().ref('flies');
allFlies.on('value', function(snapshot){
var myObj = snapshot.val();
var array = Object.keys(myObj).map(key => myObj[key])
//FORMAT THE DATA FOR THE FLYCARDS
const flyItems = array.map((fly, index) =>
<div className="flyCard" key={index} id={fly.id}>
<h3>{fly.name}</h3>
<img src={fly.image}/>
<div className="details">
<p>Hook size: {fly.hooksize}</p>
<p>Thread: {fly.thread}</p>
<p>Hackle: {fly.hackle}</p>
<p>Link: <a href={fly.youtube}>Youtube</a></p>
</div>
</div>
);
//ASSIGN FLYCARDS TO STATE FOR DISPLAY
this.setState({flies:flyItems})
}.bind(this))
}
render() {
return (
<div className="flies">
<h1>Fly test</h1>
<div>
{this.state.flies}
</div>
</div>
);
}
}
export default Flies;
That will render images with broken links. However, will work, because it's referencing the import directly. The problem is that I'm not sure how to make the {Adams} part dynamic, which is why I'm loading the path (./images/adams.jpg) from Firebase. I believe that the relevant path changes when Webpack compiles everything, which would explain why it's not working. Still, I'm not sure what the proper fix is here, even after reading up on other people having similar problems for several hours now. Any help would be appreciated!!