I'm using create react app and I need to assign props values to a styles of the component. In this case background image 'url' is need to pass as props to styles.
I have tried a lot of solutions but none of them worked
I'm making a component named HeroSection with props including backgroundURL and videoURL, I'm then using a statement to assign backgroundImage if the prop videoURL is empty
Home.js
import React from "react";
import HeroSection from "./components/HeroSection";
function Home() {
return (
<div className="home">
<HeroSection
firstLine="Not just a team,"
secondLine="We are a "
autoType={[
"family of rebels",
"movement of ideas",
"collection of culture",
]}
backgroundURL="../assets/hero_pic.jpg"
videoURL=""
/>
</div>
);
}
export default Home;
HeroSection.jsx
import React from "react";
import Typed from "react-typed";
function HeroSection(props) {
return (
<div
className={
props.videoURL === "" ? "hero-section img-background" : "hero-section"
}
style={{
backgroundImage:
props.videoURL === "" ? `url(${this.props.backgroundURL})` : "none",
}}
>
<h2>
<span className="first-line">{props.firstLine}</span>
<br />
<span className="second-line">{props.secondLine}</span>
<Typed
strings={props.autoType}
typeSpeed={40}
loop={true}
backDelay={2000}
backSpeed={20}
/>
</h2>
</div>
);
}
export default HeroSection;
I HAVE ALSO TRIED THESE STATMENTS AND NONE OF THEM WORKED
props.videoURL === "" ? `url(${props.backgroundURL})` : "none",
props.videoURL === "" ? `url('file://${props.backgroundURL}')` : "none",
So the solution was very simple
It's due to how webpack handle your assets. Since I pass it just as a string, it can't know that it needs to bundle your png as an asset. In HeroSection I added import backgroundPic from '../assets/hero_pic.jpg' and then used it in the props backgroundURL={backgroundPic} of HeroSection
Thanks for #user3252327 for commenting the solution
Related
The bounty expires in 5 days. Answers to this question are eligible for a +50 reputation bounty.
andrilla wants to draw more attention to this question:
I would love to see some ideas of what might be causing this and how I might fix it. Ideally I'd love an actual answer, but just some good ideas of what I might try would be super helpful.
#next/font
Uses Next.js with TypeScript and Tailwind CSS
This is my first time using the new #next/font package. I followed Next.js' tutorial, and it was easy to set up. I'm using both Inter and a custom local typeface called App Takeoff. To actually use both of these typefaces, I'm using Tailwind CSS, where Inter is connected to font-sans and App Takeoff is connected to font-display.
Everything works except in one spot
I have done plenty of testing between files, and for some reason both typefaces work everywhere except my Modal component.
Example
index.tsx
modal.tsx via index.tsx
As you can see, the typefaces work just fine when they aren't inside the modal, but as soon as they're in the modal they don't work.
Here's some relevant code:
// app.tsx
import '#/styles/globals.css'
import type { AppProps } from 'next/app'
import { Inter } from '#next/font/google'
const inter = Inter({
subsets: ['latin'],
variable: '--font-inter'
})
import localFont from '#next/font/local'
const appTakeoff = localFont({
src: [
{
path: '../fonts/app-takeoff/regular.otf',
weight: '400',
style: 'normal'
},
{
path: '../fonts/app-takeoff/regular.eot',
weight: '400',
style: 'normal'
},
{
path: '../fonts/app-takeoff/regular.woff2',
weight: '400',
style: 'normal'
},
{
path: '../fonts/app-takeoff/regular.woff',
weight: '400',
style: 'normal'
},
{
path: '../fonts/app-takeoff/regular.ttf',
weight: '400',
style: 'normal'
}
],
variable: '--font-app-takeoff'
})
const App = ({ Component, pageProps }: AppProps) => {
return (
<div className={`${inter.variable} font-sans ${appTakeoff.variable}`}>
<Component {...pageProps} />
</div>
)
}
export default App
// modal.tsx
import type { FunctionComponent } from 'react'
import type { Modal as ModalProps } from '#/typings/components'
import React, { useState } from 'react'
import { Fragment } from 'react'
import { Transition, Dialog } from '#headlessui/react'
const Modal: FunctionComponent<ModalProps> = ({ trigger, place = 'bottom', className, addClass, children }) => {
const [isOpen, setIsOpen] = useState(false),
openModal = () => setIsOpen(true),
closeModal = () => setIsOpen(false)
const Trigger = () => React.cloneElement(trigger, { onClick: openModal })
const enterFrom = place === 'center'
? '-translate-y-[calc(50%-12rem)]'
: 'translate-y-full sm:-translate-y-[calc(50%-12rem)]'
const mainPosition = place === 'center'
? '-translate-y-1/2'
: 'translate-y-0 sm:-translate-y-1/2'
const leaveTo = place === 'center'
? '-translate-y-[calc(50%+8rem)]'
: 'translate-y-full sm:-translate-y-[calc(50%+8rem)]'
return (
<>
<Trigger />
<Dialog open={isOpen} onClose={closeModal} className='z-50'>
{/* Backdrop */}
<div className='fixed inset-0 bg-zinc-200/50 dark:bg-zinc-900/50 backdrop-blur-sm cursor-pointer' aria-hidden='true' />
<Dialog.Panel
className={`
${className || `
fixed left-1/2
${
place === 'center'
? 'top-1/2 rounded-2xl'
: 'bottom-0 sm:bottom-auto sm:top-1/2 rounded-t-2xl xs:rounded-b-2xl'
}
bg-zinc-50 dark:bg-zinc-900
w-min
-translate-x-1/2
overflow-hidden
px-2 xs:px-6
shadow-3xl shadow-primary-400/10
`}
${addClass || ''}
`}
>
{children}
</Dialog.Panel>
<button
onClick={closeModal}
className='
fixed top-4 right-4
bg-primary-600 hover:bg-primary-400
rounded-full
h-7 w-7 desktop:hover:w-20
overflow-x-hidden
transition-[background-color_width] duration-300 ease-in-out
group/button
'
aria-role='button'
>
Close
</button>
</Dialog>
</>
)
}
export default Modal
I hope this information helps. Let me know if there's anything else that would be helpful to know.
Helpful Update
Thank you Jonathan Wieben for explanation of why this isn't working (See Explanation). The issue simply has to do with the scope of the applied styles, and Headless UI's usage of the React Portal component. If anyone has some ideas of how I can either change where the Portal is rendered or change the scope of the styles, that would be super helpful. Jonathan Wieben pointed out a way to do this, however—from my testing—it doesn't work with Tailwind CSS.
The Dialog component you are using renders in a portal (see here).
you typically want to render them as a sibling to the root-most node of your React application. That way you can rely on natural DOM ordering to ensure that their content is rendered on top of your existing application UI.
You can confirm this by inspecting your modal DOM element in your browser and seeing if it is indeed placed outside the div wrapper from your App component (I suspect it is).
If so, this is the explanation for why the modal content does not render with the expected font: It is rendered outside the component that defines the font.
To get around this, you could define your font on a higher level, e.g. in your head like described here: Next docs.
how to load imported image path to img tag src from the component props. please help
import amy from "./amy.jpg";
<AvatarProfileIcon icon="amy" />
<img src={props.icon} />
https://codesandbox.io/s/load-icon-through-props-in-img-src-9qzox5
the string can't indicate variable's name.
change your code like this.
function objectfromstring(string){
switch(string){
case 'amy' : return amy
case 'andrew' : return andrew
case 'ava' : return ava
case 'ben' : return ben
case 'brian' : return brian
default : return amy
}
}
function Avataruserprofile(props) {
return (
<div className="avataruser">
<img src={objectfromstring(props.icon)} />
</div>
);
}
you mistyped your code in your html code(not amy but ami) sandbox
I added code
https://codesandbox.io/s/load-icon-through-props-in-img-src-forked-wc5xp1
Try wrapping your imported image inside curly braces {} instead of double quotes "" since they are being used for strings.
import amy from "./amy.jpg";
export default function App() {
return (
<div className="App">
<AvatarProfileIcon icon={amy} />
</div>
);
}
Live Demo
import "./styles.css";
import AvatarProfileIcon from "./AvatarProfileIcon";
import amy from "./amy.jpg";
export default function App() {
return (
<div className="App">
<AvatarProfileIcon icon={amy} />
</div>
);
}
Code Sandbox
I want to make shopping app in react but i did wrong thing where i dont know.What is the error?
I want to import images and looping them according to "sku number" but i just fetch header of images. I can't see images, i can't fetch them.
<img src="../src/images/{{$product.sku}}.jpg" alt={product.title} />
This is the fetch code . I have tried and i'm trying different codes for fetching but it doesn't work.
Products.js :
import React, { Component } from "react";
import a from "./a.json";
import "./styles.css";
class Products extends Component {
state = {
products: a.products
};
render() {
const productItems = this.state.products.map(product => (
<div className="col-md-4">
<div
className="thumbnail text-center"
style={{ backgroundColor: "black" }}
>
<a href={product.id} onClick={this.props.handleAddToCart}>
<img src="../src/images/{{$product.sku}}.jpg" alt={product.title} />
</a>
</div>
</div>
));
return <div className="row">{productItems}</div>;
}
}
export default Products;
And the sight of folders:
And the sku numbers for matching with photo's names.
The sight of page
Try changing this line:
<img src="../src/images/{{$product.sku}}.jpg" alt={product.title} />
for:
<img src={`../src/images/${product.sku}.jpg`} alt={product.title} />
In order for you to embed Javascript into any React component, remember to always enclose your code block in {brackets}. Since backticks belong to Javascript syntax, the enclosing brackets must be added.
I have a React project and this is my first time using it.
I have a JavaScript in the container that import a JavaScript within the components.
This is my containers file
Restorans.js
import React, { Component } from 'react';
import Restoran from "./components/Restoran/Restoran";
import classes from "./Restorans.module.css";
class Restorans extends Component{
constructor(props){
super(props);
this.state = {
restorans:
[
{id:1, nama: "Restoran A", alamat: "This is address Restoran A", nomorTelepon : "0217352333"},
{id:2, nama: "Restoran B", alamat: "This is address Restoran B", nomorTelepon : "0217352334"},
{id:3, nama: "Restoran C", alamat: "This is address Restoran C", nomorTelepon : "0217352335"}
],
isLoading: true
}
}
componentDidMount() {
console.log("componentDidMount()");
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
}
loadingHandler = () => {
const curretIsLoading = this.state.isLoading;
this.setState({isLoading: !(curretIsLoading)});
console.log(this.state.isLoading);
}
render() {
console.log("render()")
return(
<React.Fragment>
<div className={classes.Title}> All Restoran </div>
<div className={classes.Restorans}>
{this.state.restorans.map(restoran =>
<Restoran
key={restoran.id}
nama={restoran.nama}
alamat={restoran.alamat}
nomorTelepon = {restoran.nomorTelepon}
/>
)}
</div>
</React.Fragment>
);
}
}
export default Restorans;
and this is my components
Restoran.js
import React from "react";
import classes from "./Restoran.module.css";
const Restoran = props => {
return(
<div className={classes.Restoran}>
<h3>
{props.name}
</h3>
<p>
Alamat: {props.alamat}
</p>
<p>
Nomor Telepon: {props.nomorTelepon}
</p>
</div>
)
}
export default Restoran;
My folder library is as follow
When I run npm start on my terminal. I receive this error:
Module not found: Can't resolve './components/Restoran/Restoran' in 'C:\Users\[REDACTED]\projectreact\frontend-projectreact\src\containers\Restorans'
To my own understanding, there shouldn't be any error. I tried to add .js on the end but it still has the same problem. Where did I go wrong?
It looks like you are within the containers directory in Restorans.js.
If you want to access Restoran.js from components, you have to go two levels up and out of containers, so change your import in containers/Restorans.js to:
import Restoran from "./../../components/Restoran/Restoran";
The ../../ part will take you to the root parent directory where both containers and components live as children/sub-directories by moving you up two folders.
As far as CSS, I usually import it one place from in the root <App/> component after a normalizer/CSS Reset.
Firstly,(just an advice) try not to name your files same. I see Restorans.module.css both in Restoran and Restorans. It might get clumsy to do so. And next thing is if you want to import css file
import "../Restoran/Restoran.module.css"
or any specific element then
import {classes} from "../Restoran/Restoran.module.css"
Also , check the path as ,if you are working on Restoran.js then
"../../components/Restoran/Restoran"
.. -> changes to root and then from there you can change your folder and access the required components.
Defining the path as './../../components/Restoran/Restoran' should help.
You use incorrect relative path (in Restorans.js), try:
import Restoran from "../../components/Restoran/Restoran";
Also you can set up aliases to have absolute paths (import Restoran from '#components/Restoran/Restoran')
I am building a web app with ReactJS, on the home page I am using a ternary operator two render two different Fragment according to the state( if true or false).
my Code looks like:
import React, { Component, Fragment } from 'react'
import { Link } from 'react-router-dom'
class Home extends Component {
state = {
citySearch : false
}
render(){
return (
<div className="home-main">
{ !this.state.citySearch ? (
<Fragment>
<h2 className="home-heading">Search Cafés from your</h2>
<div className="home-buttons">
<button className="home-buttons">Near You</button>
<span>or</span>
<button onClick={this.ActivateCitySearch} className="home-buttons">City</button>
</div>
</Fragment>
)
: (
<Fragment>
<h2 className="home-heading">Search Cafés from your</h2>
<input className="search-café" placeholder="Enter your location"/>
<Link className="search-input"><i className="fas fa-search"></i></Link>
</Fragment>
)
}
</div>
)
}
}
export default Home
The code works but I get the following in the console
InvalidValueError: not an instance of HTMLInputElement
Does anyone know how to get rid of this error??
Thanks,
J