Properties background image not working [React] - javascript

I'm trying to set the background image of a div depending on the value of a component property, the background doesn't show, however it does show when I harcode the background-image property in the css file.
Here is the component code :
import React, { Component } from "react";
import "./Banner.css";
export default class Banner extends Component {
render() {
const style = {
backgroundImage: `url("${this.props.image}")`,
};
return (
<div className="banner" style={style}>
Chez vous, partout et ailleurs
</div>
);
}
}
Here is the Banner.css file:
.banner {
/* background-image: url("../assets/images/moutains.png"); */
background-size: cover;
height: 170px;
border-radius: 20px;
text-align: center;
vertical-align: middle;
line-height: 170px;
font-size: 2.5rem;
color: #fff;
}
In the parent component:
<Banner image="../assets/images/moutains.png" text="" />
EDIT: Complete code and assets here: https://github.com/musk-coding/kasa
codesandbox: https://codesandbox.io/s/github/musk-coding/kasa
Thanks in advance for your help

Since, you are trying to access the image directly in your Component using the inline CSS. You must move your image to the public folder.
CODESANDBOX LINK: https://codesandbox.io/s/image-relative-path-issue-orbkw?file=/src/components/Home.js
Code Changes:
export default class Home extends Component {
render() {
const imageURL = "./assets/images/island-waves.png";
return (
<div className="container">
<div className="slogan" style={{ backgroundImage: `url(${imageURL})` }}>
Chez vous, partout et ailleurs
</div>
<Gallery />
</div>
);
}
}
NOTE: From React Docs, you can see the ways to add images in Component. create-reac-app-images-docs. But since you want an inline CSS, in that case we have to move our assets folder into the public folder to make sure that the image is properly referenced with our component.

Related

React doesn't insert image as background

I'm creating a web page and I took a jpg and pgn image to put as a background.
But by no means does it appear on the page.
import './Entrada.css'
const Entrada = () => {
return(
<div style={{
backgroundImage: "url(/secoes_02.jpg)"
}}>
<div><img src='secoes_02.jpg'/></div>
<div className='texto'>testatastastasta</div>
</div>
)
}
export default Entrada
In the code above I can place the image as a figure, but I cannot as a background.
I've already tried to insert it by Css and tried import to.
.geral{
background: url("/public/img/partes/secoes_02.jpg");
}
But in no way does it appear in my react.
I already reinstalled the nodejs packages and changed the folder location.
And the error continues.
Has anyone experienced this?
Try it plz. It works for me.
import footer from '../../assets/images/footer.png';
function MyComponent() {
return (
<footer style={{ background: `url(${footer})`, backgroundSize: "contain" }}>
Try this.. worked for me
js:
render() {
return (
<div className="bgimage">
<div className='texto'>testatastastasta</div>
</div>
)
}
css:
.bgimage {
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
background-image: url(https://business.adobe.com/content/dam/dx/us/en/products/magento/open-source/open-source-marquee-2x.png.img.png);
}
Height is given 100%, based on your need you can adjust.

Add svg image as icon for Input of Semantic UI

I'm using Input from Semantic UI in order to create a search input:
import React from 'react';
import { Input } from 'semantic-ui-react';
export default ({ placeholder, onChange }) => {
return (
<Input
icon="search"
icon={<img src={searchIcon} />}
iconPosition="left"
placeholder={placeholder}
onChange={onChange}
/>
);
};
It works and looks good.
The problem is that I need to change its icon with an svg image. So the svg is imported in the file and used like this:
import React from 'react';
import { Input } from 'semantic-ui-react';
import searchIcon from '../../assets/icons/searchIcon.svg';
export default ({ placeholder, onChange }) => {
return (
<Input
icon={<img src={searchIcon} />}
iconPosition="left"
placeholder={placeholder}
onChange={onChange}
/>
);
};
The problem is that it puts the icon outside of the input and on the right side of it.
It should be inside the input and on the left part.
There were no styling changes after the svg was added, why isn't it in the same position as the original icon?
Most likely semantic-ui adding special styles when we add some icon by attribute "icon". Semantic-ui-react doesn't support custom icons. :,(
In the type declaration we can read:
/** Optional Icon to display inside the Input. */icon?: any | SemanticShorthandItem<InputProps>
My proposition: add some styles to CSS, like me in the sandbox
.input {
position: relative;
width: fit-content;
display: flex;
justify-content: center;
align-items: center;
}
img {
position: absolute;
right: 5px;
width: 10px;
}
I got it working by passing a custom component where the svg image is wrapped by an i tag that has a an icon class:
const CustomIcon = (
<i className="icon">
<img width={38} height={38} src={searchIcon} />
</i>
);
const App = () => {
return (
<Input icon={CustomIcon} iconPosition="left" placeholder="placeholder" />
);
};
The benefit to this approach is that you can change the iconPosition without it breaking the styling with this approach.
To give more context the icon getting displayed at the right position is due to the styles applied to this selector: .ui.icon.input>i.icon. Because it expects an i tag the styles won't be applied if you don't wrap the image between i tags.

Styling a nested styled-component from an outer one

Using styled-components, I am trying to style a nested <Input /> component that I have created, which is being used within a different component that has a dropdown appear when typing. I need to add padding-left: 3rem to this nested input but I cannot access it from the component <Dropdown />.
<Dropdown
options={options}
/>
The above is imported where I need it. I need to access the below input from the above <Dropdown />.
<div>
<Input {...props}/> // I need to edit the padding in this component
// rendered input unique to this new component would go here
</div>
The above <Input /> is imported from another component which is used in all instances where I require an input.
export const Dropdown = styled(DropDown)`
padding-left: 3rem !important;
`;
The component works fine but this fails to affect the inner padding of the Input that I need to target.
What do I do?
From what you've said, I'd suggest that the dependency of padding the Input component is with your Dropdown (which you seem to realise already).
Therefore you'd be better off having that "unqiue" styling coupled with your Dropdown component via a wrapping styled component within it.
The following example is crude (and by no means complete or working), but hopefully it illustrates how the ownership of the padding-left should be within the Dropdown and not a sporadic styled component floating some where else in your code base.
./Input/Input.jsx
const Input = ({ value }) => (
<input value={value} />
);
./Dropdown/styled.js
const InputWrapper = styled.div`
position: relative;
padding-left: 3rem !important; /* Your padding */
`;
const Icon = styled.div`
position: absolute;
top: 0;
left: 0;
width: 3rem;
height: 3rem;
background: blue;
`;
const Menu = styled.ul`/* whatever */`;
./Dropdown/Dropdown.jsx
import Input from '...';
import { InputWrapper, Icon, Menu } from './styled';
const Dropdown = ({ options }) => (
<div>
<InputWrapper>
<Icon />
<Input value={'bleh'} />
</InputWrapper>
<Menu>{options}</Menu>
</div>
);
This setup will promote reusable self-contained components.
Figured out the solution below:
export const StyledInput = styled.div`
&& #id-for-input { // specifically on the <Input />
padding-left: 3rem !important;
}
`;
<StyledInput>
<Dropdown />
</StyledInput>

CSS doesn't apply to a component

I have a react component that is wrapped up in div:
AccountLogin.jsx:
import './AccountLogin.css';
export default observer(() => (
<div className="content">
Something here
</div>
));
AccountLogin.css:
.content {
color: blue;
background-color: blue;
margin: 500px;
}
But the css doesn't apply to my rendered component AccountLogin.
Any ideas why that could happen?
Looking at rfx-stack source, I can see that files suffixed with .global.css are imported in global scope where as others are imported as css-modules.
So you can either rename your file to AccountLogin.global.css or use the imported class name:
import styles from './AccountLogin.css';
Within component:
<div className={styles.content}>...</div>

'React' is defined but never used

I am following the official reactjs instructions to create a sample app. My node version is 6.9.0.
I created sample react app which is supposed to display a empty tic tac toe table according to the official website using following instructions:
npm install -g create-react-app
create-react-app my-app
cd my-app
changed to my-app directory
removed the default files inside the source directory as directed. Now
my index.js looks like this
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
Then I ran yarn start
But all I see is blank screen no tic tac toe table. And couple warnings in the console saying
Compiled with warnings.
./src/index.js
Line 1: 'React' is defined but never used no-unused-vars
Line 2: 'ReactDOM' is defined but never used no-unused-vars
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
You missed last parts in steps 4 & 5:
Add a file named index.css in the src/ folder with this CSS code.
Add a file named index.js in the src/ folder with this JS code.
index.css
body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}
ol, ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: "";
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
index.js
class Square extends React.Component {
render() {
return (
<button className="square">
{/* TODO */}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square />;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
You should create some component/element/, maybe style it, then call ReactDOM to render your component to the underlying html and then you will have it.
React is used to handle JSX and creation of React component
ReactDOM in your simple case will be used to render created element to dom.
See here : https://reactjs.org/blog/2015/10/01/react-render-and-top-level-api.html
So ading something like
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
to your code, you will get something if in your index.html there is element with id="root" inside <body> tag
This simply means your project has eslint configured to catch unused variables.
If you use JSX or anything React within that file the warning will go away just like suggested by zmii in his answer.
But i am writing this answer because someone showed me their code and they were facing the same problem.
Their code :
import React from 'react';
const person = () => {
return "<h2>I am a person!</h2>"
};
export default person;
The problem in the above code was that while returning, he used double quotes. So instead of JSX, it was returning string and therefore they were getting error that React was never not used.
Conclusion: Syntax are important so keep in mind, specially if you are starting out.
Hope this helps someone.
ESlint needs to be configured to work with React JSX. This excellent article has all the details.

Categories