reach-router background-image not displaying correctly sometimes - css

I've created a create-react-app project and I'm just starting to add routing to it now with reach-router. I have a simple TitleHeader component with a background-image that I use with the components for each of the routes. They mostly work, but whenever I navigate to one in particular (DissectionGame), the background image doesn't appear and then after that, it doesn't appear for any of the other components either.
Below are relevant snippets, though they really don't show the problem. At this level, all of the components are really the same and if I comment out the other nested components in the DissectionGame component, it works as well. Given that, I assume the problem has something to do with those components, but I just have no idea what to look at and what might affect the background-image in the TitleHeader component.
Does anyone have any clues as to what might be happening? Can the path to the image somehow get stomped on and if so, how? I've only been working in React for a couple months now so it's all still pretty fresh. I'd appreciate any suggestions!
function App() {
return (
<AppStyle>
<HeaderNav />
<Router>
<Home path="/" />
<Help path="help" />
<Games path="games" >
<GamesInfo path="/" />
<DissectionGame path="dissection" />
</Games>
</Router>
</AppStyle>
);
}
const HeaderBlock = styled.div`
background-image: url(./dark-paths.png);
background-size: auto;
font-family: 'Roboto', sans-serif;
font-weight: 400;
font-size: 24px;
color: #c2d5db;
padding: 15px 0px;
margin: 5px 0px 10px;
`;
const TitleHeader = ({title}) => {
return (
<HeaderBlock>
{title}
</HeaderBlock>
)
}
const Home = () => {
return (
<React.Fragment>
<TitleHeader title="Welcome to Leading Step!" />
</React.Fragment>
)
}
const DissectionGame = () => {
return (
<React.Fragment>
<TitleHeader title="Sentence Dissection" />
/* Other game components... */
</React.Fragment>
)
}

I suggest you try to remove the . in the URL to make sure that the images is loading from the root of the server, not the relative path of the current route.
Also, don't forget to put your images under the public folder.
background-image: url(/dark-paths.png);

Related

NavLink returns active to all links and no solution in SO seems to work

It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.
(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)
Here's my return statement and the styled-components below it:
return (
<>
<GlobalStyles />
<Router>
<Header />
<Wrapper>
<NavBar>
<NavLink
to="/search"
exact
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
Search song
</NavLink>
<NavLink
to="/weekly-thread"
exact
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
Weekly thread
</NavLink>
<NavLink
to="/game"
exact
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
Game
</NavLink>
</NavBar>
</Wrapper>
</Router>
</>
);
};
const Wrapper = styled.div`
width: 100vw;
height: 100vh;
position: absolute;
z-index: -1;
`;
const NavBar = styled.div`
display: flex;
padding: 20px 20px;
position: relative;
gap: 20px;
font-size: 18px;
a {
text-decoration: none;
}
.nav-link {
color: blue;
&:inactive {
color: black;
}
}
`;
EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.
SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:
<NavLink to="/search" exact className={(isActive) => {
console.log(isActive);
isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>
Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.
After console.logs here, there and everywhere, something struck my attention: isActive appears as an object on the console. That's why I was always getting the same result.
When I changed the condition on the ternary operator to isActive.isActive ? I started getting the expected results.
Router
You might want to read up on the docs.
The primary components page explains why you would need a router.
It provides information for the other components; IE what the current route is.
NavLink
NavLink should be able to set their active class themselves, based on if the router is matching on the to props of the NavLink
see this CodePen for an example.
Note that you would still need need to provide the CSS for the class that is applied. If you're using a framework like bootstrap, or material-ui; they would usually have a .active css styling already in there by default.
CSS
The css rule might be incorrect, there seems to be a colon at &:inactive which probable should be .inactive class:
.nav-link {
color: blue;
&.inactive {
color: black;
}
}
codepen
You should be able to remove your className property from NavLink.
Remove:
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
It's unnecessary as React-Router already adds the .active class to the active link, so what you're doing with that property is no doubt creating the weirdness.
You can just style the a.active however you want.

Override margin in Separator Component of Fluent UI using React

I'm trying to override the margin attribute of a Separator component using Microsoft's Fluent UI using React. The top-margin appears to default to 15px and I would like it to be less than that.
Here's a screenshot:
The beige color section above is defaulting to 15px and I'd like to shrink it but I can't seem to find the correct css to do so.
Here's the code I have thus far:
const separatorStyles = {
root: [
{
margin: 0,
padding: 0,
selectors: {
'::before': {
background: 'black',
top: '0px'
}
}
}
]
};
export default class Home extends Component {
render() {
return (
<Stack verticalAlign="center" verticalFill gap={15}>
<Component1/>
<Separator styles={separatorStyles} />
<Component2 />
</Stack>
);
}
}
I've tried placing the margin: 0 where it currently is at the root level and also nested below the ::before but neither have worked.
The only other potential clue I have comes from an inspection of the styles in Chrome's DevTools which yields:
Any ideas would truly be appreciated!
Thanks for your time!
The 15px actually came from the gap prop that was passed to the Stack component. It takes care of adding that css class to children elements to ensure the proper margins exist.
I believe removing it altogether should solve your concern, such as in this example (link to working code):
<Stack verticalAlign="center" verticalFill>
<button>Button1</button>
<Separator>no margin</Separator>
<button>Button2</button>
<Separator />
<button>Button3</button>
</Stack>
However, it is worth noting that the Separator expects to render some text, so you might have trouble getting it to be the exact height you want (as font-size is a concern for the Separator). If that's the case, you might be better off just making your own control to render a 1px line with a simple div or span.
Also you can you use this approach with styled-component:
import React from 'react'
import {Separator} from '#fluentui/react'
import styled from 'styled-components'
const StyledSeparator = styled(Separator)`
&::before {
margin-top: 15px;
}
div {
//any styles for separator-content
}
`
export const Divider = ({children}) => {
return <StyledSeparator>{children}</StyledSeparator>
}

Ho do I add common css for stenciljs web-components

I am creating bunch of web-components, not sure how do I create common css for stenciljs web-components.
Based on documentation I can add globalStyle: 'src/global/app.css',
But it seems i can only share css variables. e.g.
:root {
--font_color: #484848;
--bg_color--light: #f9f9f9;
}
if I want to have common base css for buttons e.g.
button {
border-radius: 5px;
padding: 2px 10px;
}
Which i want to share across all the components | Not sure how to achieve that.
Thanks in advance for suggestions.
The globalStyle stylesheet gets distributed along with your app and can indeed be used to write global CSS. E. g. for the www output target, it gets generated as /build/<namespace>.css, and you can then include it into your app with a link:
<link rel="stylesheet" href="/build/my-app.css" />
However you can't use it to provide base css for elements that are inside a custom element with Shadow DOM enabled (i. e. if you have shadow: true in the component decorator).
So, as a solution you can use sass partials and modules to achieve what you're trying to do.
// src/styles/partials/_button.scss
button {
border-radius: 5px;
padding: 2px 10px;
}
// src/components/my-button/my-button.tsx
#Component({
tag: my-button,
shadow: true,
styleUrl: 'my-button.scss',
})
export class MyButton {
render() {
return <button>Click me</button>
}
}
// src/components/my-button/my-button.scss
#use '../../styles/partials/button';
The Stencil docs are a bit unclear on this issue. It took me a while to realize the globalStyle config doesn't actually do anything to apply global styles to components with shadow DOM.
If you wish to use the globalStyle globally across all components, you can try the following:
Link the globalStyle inside your index.html
Also link the globalStyle inside each of your components
The components may seem strange with a style link, but it actually works.
render() {
return (
<Host>
<link rel="stylesheet" href="/build/my-app.css" />
RENDER THIS COMPONENT WITH GLOBAL STYLES
</Host>
);
}

How to make a block appear in reactjs?

Hi and thanks for the great work here. I'm pretty new in reactjs and I'm struggling to make it work with sandbox like jsfiddle.
I have a div called "app-content" tht is supposed to appear in the middle of the document just like the following :
For some reasons , I cant make the following thing on my sandbox , and I get the following : https://jsfiddle.net/w7sf1er6/8/
JS here
export default class App extends React.Component {
render() {
return (
<div className="app-content">
</div>
);
}
};
ReactDOM.render (
<App />,
document.getElementById('root')
);
and CSS here
html {
background-color: #e3e3e3;
font-family: regular, arial, sans-serif; }
body {
margin: 0 !important;
padding: 0 !important; }
a {
text-decoration: none; }
.app-content {
width: 1200px;
height: 500px;
margin-left: auto;
margin-right: auto;
background-color: white; }
What am I mising ? I need to make it work on JSfiddle so I can share it with others developers. I wuld appreciate some help from our community.
Thanks.
You must install react-blocks via npm first if you haven't already.
Like so, npm install react-blocks
Once you have done this, you will need to import/require react-blocks within your react code.
// using an ES6 transpiler
import Block from 'react-blocks';
// not using an ES6 transpiler
var Block = require('react-blocks');
Next, the layout:
// Normal Flex layout
const App = () => {
return (
<Block layout>
<div>Alpha</div>
<div>Beta</div>
</Block>
);
};
// Reverse Flex layout
const Reverse = () => {
let { reverse } = styles;
return (
<Block style={reverse.block} layout vertical reverse>
<div>Alpha</div>
<div flex>Beta</div>
</Block>
);
};
Feel free to read more on the process here.
Hope this helps!
Your React component is not rendering to the div. You can see errors in the console log and doing "view frame source" on the HTML output pane will show you that the "div" element hasn't been replaced.
As Chris suggested, just start from a JSFiddle example that sets up React correctly.
The example above mainly differs from your code in that it imports React definitions.
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js" />

CSS text align justify big spaces

To format paragraphs I use text-align:justify, but I have one problem that there are big spaces between words, for IE the solution is to use text-justify: distribute;, but Chrome doesn't support this, my question is what should I use for Chrome and Firefox
Example of big spaces: http://jsfiddle.net/L5drN/
Give negative values as you prefer for word-spacing..
ex:
text-align:justify;
word-spacing:-2px;
Works for me and Hope this helps :)
Use:
word-break: break-all;
And Ok!
Consider using hyphenation (manual, CSS, server-side, or client-side JavaScript), see e.g. answers to Can I use CSS to justify text with hyphenating words at the end of a line?
Hyphenation tends to help a lot when there are long words in the text.
You can still keep text-justify: distribute, as it can improve the result on supporting browsers, and it can be expected to gain support, as it in the CSS standardization track (in CSS Text Module Level 3 WD).
text-align: justify;
text-justify: distribute;
text-align-last: left;
hope this will help you
I got something satisfying by combining both methods:
enable hyphens (using two variants for compatibility)
negative word spacing (no more than -0.05em otherwise text get condensed)
div.justify {
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
word-spacing: -0.05em;
}
div.font {
font-size: 110%;
}
<div class="justify font">In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. It is also used to temporarily replace text in a process called greeking, which allows designers to consider the form of a webpage or publication, without the meaning of the text influencing the design.</div>
How do you want to format the paragraphs? Do you mean the width, height, letter spacing or word spacing?
Have you tried using the text-align CSS tag?
text-align:center
Or the word-spacing CSS tag?
word-spacing:10px
I have an alternate solution to get rid of the big spacing between word
first you should know one thing that text-align:justify is used only when you are rendering your text component on wider screen so in my case I was using it on card custom component so I simply increase the width of my card component and this helps me hope it will help you to.
Card.js
import React from 'react';
import styles from './Card.module.css'
const Card = (props) => {
return (
<div className={styles.card}>
{props.children}
</div>
);
} ;
export default Card;
Card.module.css
.card {
height: 30rem;
width: 25rem;
margin: 0 20px 10rem;
text-align: justify;
}
Calling card component in HOC
import React, { useEffect, useState } from "react";
import projectStyles from "./project.module.css";
import Card from "../UX/Card";
import axios from "axios";
const Project = () => {
const [loadedProjects, setLoadedUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
try {
const responseData = await axios("api/projects");
setLoadedUsers(responseData.data.projects);
} catch (err) {}
};
fetchUsers();
}, []);
const displayHandler = (
<div className={projectStyles.projectHolder}>
{loadedProjects.map((project,index) => {
return (
<Card key={index}>
<img src={project.image} alt="project" height={225} width={345} style={{marginBottom:"20px"}}/>
<p style={{fontSize:'25px' , fontWeight:'bold'}}>{project.title}</p>
<p className={projectStyles.body}>{project.info}</p>
<h4>Technologies Used</h4>
<ul key={project.image}>
{project.technology.map((tech) => {
return <li key={tech}>{tech}</li>;
})}
</ul>
</Card>
);
})}
</div>
);
return <div>{loadedProjects ? displayHandler : 'Fetching Projects...'}</div>;
};
export default Project;

Resources