trouble to show component in react - css

im using an old version of a CRUD so i think that some codes aren't working any more, but vscode is not point it like an error, so the page goes on but my content box still empty. could somone help me?
these are 4 codes that i think that should be improved...
first my header that dont show me the props.icon tasks
import './Header.css'
import React from 'react'
export default function props () {
return (
<header className = "header d-none d-sm-flex flex-column">
<h1 className="mt-3">
<i className={`fa fa-${props.icon}`}></i>{props.title}
</h1>
<p className="lead text-muted">{props.subtitle}</p>
</header>
)}
here my main.jsx which my header goes inside by import
import './Main.css'
import React from 'react'
import Header from './Header'
function props () {
return (
<React.Fragment>
<Header {...props}/>
<main className="content container-fluid">
<div className="p-3 mt-3">
{props.children}
</div>
</main>
</React.Fragment>
)
}
export default props
now my app.jsx and app.css wht render my Htmls
import 'bootstrap/dist/css/bootstrap.min.css'
import 'font-awesome/css/font-awesome.min.css'
import './App.css'
import React from 'react'
import {HashRouter} from 'react-router-dom'
import Routes from './Routes'
// import Home from '../components/home/Home'
import Logo from '../components/template/Logo'
import Navi from '../components/template/Navi'
import Footer from '../components/template/Footer'
// import props from '../../../frontend2/src/components/template/main'
function Props () {
return(
<HashRouter>
<div className="App">
<Logo />
<Navi/>
<Routes/>
<Footer />
</div>
</HashRouter>
)
}
export default Props
//////////////////////////
:root{
--bg-dark: #1a2f3a;
--logo-height: 100px;
--header-height: 100px;
--aside-width: 225px;
--footer-height: 40px;
--shadow:
0 2px 23px 0 rgba(0, 0, 0, 0.1)
0 2px 49px 0 rgba(0, 0, 0, 0.06)
}
*{
box-sizing: border-box;
font-family: 'Montserrat', sans-serif;
}
/* layout em grid */
.App {
margin: 0px;
display: grid;
grid-template-columns: var(--aside-width) 1fr;
grid-template-rows:
var(--header-height)
1fr
var(--footer-height);
grid-template-areas:
"logo header"
"menu content"
"menu footer";
height: 100vh;
background-color: #f5f5f5;
}
aside.logo{
grid-area: logo;
}
header.header{
grid-area: header;
}
aside.menu-area{
grid-area: menu;
}
main.content{
grid-area: content;
}
footer.footer{
grid-area: footer;
}
then my routes.jsx
import React from 'react'
import {Switch, Route, Redirect} from 'react-router'
import Home from '../components/home/Home'
import UserCrud from '../components/user/UserCrud'
function Props (){
return(
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/users" component={UserCrud}/>
<Redirect from="*" to="/"/>
</Switch>
)
}
export default Props
and finally but not less important my home which own my main and is my / path
import React from 'react'
import {Switch, Route, Redirect} from 'react-router'
import Home from '../components/home/Home'
import UserCrud from '../components/user/UserCrud'
function Props (){
return(
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/users" component={UserCrud}/>
<Redirect from="*" to="/"/>
</Switch>
)
}
export default Props
please help me out here, im stucked search this error by 2 days now, im prety sure that i got a sintax error, if u got this expertise please share
here are some issues from the console but i dont even know from where came this history one, pleasee...
Warning: Please use require("history").createMemoryHistory instead of require("history/createMemoryHistory"). Support for the latter will be removed in the next major release.
stack_frame_overlay_proxy_console # index.js:2178
index.js:2178 Warning: Please use require("history").PathUtils instead of require("history/PathUtils"). Support for the latter will be removed in the next major release.
stack_frame_overlay_proxy_console # index.js:2178
react-dom.development.js:88 Warning: componentWillMount has been renamed, and is not recommended for use. See react-unsafe-component-lifecycles for details.
Move code with side effects to componentDidMount, and set initial state in the constructor.
Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.
Please update the following components: HashRouter, Route, Router, Switchnull

I think you might have got a bit mixed up regarding the nature of props in the React framework. Consider reading over the documentation to get more of an overview of how we use them to structure data flow in React applications.
To put it briefly, props are the inputs that components pass to one another in order to populate the UI and update the state of an application. In functional React, we can think of them as the parameters that a function (i.e. component) takes in order to return a given output in JSX.
So when it comes to your code, naming all your component functions Props is not the same as them actually having props available to use. First, a component's parent has to pass it a prop inside the JSX, and then it has to access that prop from the function parameters before it can be used. Here is a simplified example below which will hopefully make the pattern more clear for you:
// App.jsx
function App() {
return (
<div>
<Header title={'someValue'}/>
<MainComponent />
</div>
);
};
// Header.jsx
function Header(props) {
return (
<header>
<h1>{props.title}</h1>
</header>
);
};
I see you were also trying to use props.children which is a slightly different feature and does not work in the same way. The children of a React component are any elements that that component wraps around in the instance that it is declared. The children themselves do not have to passed as props in the usual manner, but they must still be accessed from the function's parameters. In this example, the props.children of MainComponent is the div with the class child:
// App.jsx
function App() {
return (
<div>
<MainComponent>
<div class="child">
</div>
</MainComponent>
</div>
);
};
// MainComponent.jsx
function MainComponent(props) {
return (
<main>
{props.children}
</main>
);
};

Related

having issues using face detection API from Clarifai API

I have added the face detection API from Clarifai APi to my project, however, whenever i copy an image to my project and click on detects, it actually shows the image but it is not detecting the face.
see below App.js and FaceRecognition.js
import React, {Component} from 'react';
import Clarifai from 'clarifai';
import Navigation from './components/Navigation/Navigation';
import Logo from './components/Logo/Logo';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import Rank from './components/Rank/Rank';
import './App.css';
const app = new Clarifai.App({
apiKey: 'xxxxxxxxxxxx'
});
class App extends Component {
constructor() {
super();
this.state = {
input: '',
imageUrl: '',
box: {}
}
}
calculateFaceLocation =(data) => {
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - (clarifaiFace.right_col * width),
bottomRow: height - (clarifaiFace.bottom_row * height)
}
}
displayFaceBox = (box) => {
console.log(box)
this.setState({box: box});
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(
Clarifai.FACE_DETECT_MODEL,
this.state.input)
.then( response => this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log(err));
}
render() {
return (
<div className="App">
<Navigation />
<Logo />
<Rank />
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit} />
<FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
</div>
);
}
}
export default App;
FaceRecognition.js
import React from 'react';
import './FaceRecognition.css';
const FaceRecognition = ({imageUrl, box}) => {
return (
<div className='center ma'>
<div className='absolute mt2'>
<img id='inputimage' alt='' src={imageUrl} width='500px' height='auto' />
<div className='bounding-box' style=
{{top: box.topRow, right: box.rightCol, bottom: box.bottomRow, left: box.leftCol}}></div>
</div>
</div>
);
}
export default FaceRecognition;
FaceRecognition.css
bounding-box {
position: absolute;
box-shadow: 0 0 0 3px #149df2 inset;
display: flex;
flex-wrap: wrap;
justify-content: center;
cursor: pointer;
}
what am i doing wrong?
i tried copy paste from the actual Clarifai API code, but no luck
the bounding-box css is not even showing up in the console.
please help me
First of all, please don't use this client: https://github.com/Clarifai/clarifai-javascript, it has been deprecated for a while and several things in this package are very old and broken.
If you're purely developing client-side, you can use the REST endpoints directly: https://docs.clarifai.com/api-guide/predict/images (see "Javascript (REST)" snippets throughout the docs)
I also recommend to use PAT instead of API keys. This will allow you access across all your Clarifai apps with a single token.
Clarifai has changed the way to use their Api. On Clarifai Face detect model , click to use model, then you can copy the code on how to use their Api.
https://clarifai.com/clarifai/main/models/face-detection?utm_source=clarifai&utm_medium=referral&tab=versions
Then you can import your PAT and other credentials requested for in the code from Clarifai portal.
Use this as a guide https://help.clarifai.com/hc/en-us/articles/4408131744407-Integrating-Clarifai-in-your-React-Javascript-project
You are welcome 🤗

NextJS - Framer-Motion page transition doesn't fire

for some reason my NextJS page transition with framer-motion doesn't seem to work. I followed many tutorials and did a lot of research and it still doesn't work. Here's my _app.tsx code.
import '../styles/globals.css'
import '../styles/ui.css'
import '../fonts/define.css'
import { AppProps } from 'next/app'
import Layout from '../layouts/dashboard'
import Sidebar from '../components/Sidebar'
import { AnimatePresence, motion } from 'framer-motion'
const App = ({ Component, pageProps }: AppProps) => {
return <main>
<Sidebar/>
<AnimatePresence>
<motion.div initial={{opacity: 0}} animate={{opacity: 1}} exit={{opacity: 0}} className="content">
<Component {...pageProps} />
</motion.div>
</AnimatePresence>
</main>
}
export default App
When I switch between routes the transition just doesn't fire. It only fades in on initial load, then opacity: 1 style is applied to .content div and that's it.
Thank you for your help!
I figured it out. I needed to add key attribute to the <motion.div> div. Read more here https://www.framer.com/docs/animate-presence/#unmount-animations

Theme with React and Redux

i am trying to make a theme system on a react project that uses redux with a reducer that manages themes according to the user's local storage. But here my problem is that I used css files to define my styles on all of my components. However, I have all my logic with 2 javascript objects for light or dark mode. So I can't use js in css files unless I use css variables but I don't know how.
Here is my structure :
In my app.js I imported useSelector and useDispatch from react redux to access the global state :
import React from 'react';
import './App.css';
import Footer from './components/Footer';
import Header from './components/Header';
import Presentation from './components/Presentation';
import Projects from './components/Projects';
import Skills from './components/Skills';
import Timeline from './components/Timeline';
import { switchTheme } from './redux/themeActions';
import { useSelector, useDispatch } from 'react-redux';
import { lightTheme, darkTheme } from './redux/Themes';
function App() {
const theme = useSelector(state => state.themeReducer.theme);
const dispatch = useDispatch();
return (
<div className="App">
<Header />
<input type='checkbox' checked={theme.mode === 'light' ? true : false}
onChange={
() => {
if(theme.mode === 'light') {
dispatch(switchTheme(darkTheme))
} else {
dispatch(switchTheme(lightTheme))
}
}} />
<div className="top">
<div className="leftPart">
<Presentation />
<Skills />
</div>
<Timeline />
</div>
<Projects />
<Footer />
</div>
);
}
export default App;
and in themes.js I have my 2 objects which represent the themes :
export const darkTheme = {
mode: 'dark',
PRIMARY_BACKGROUND_COLOR: '#171933',
SECONDARY_BACKGROUND_COLOR: '#1e2144',
TERTIARY_BACKGROUND_COLOR: '#0a0c29',
PRIMARY_TEXT_COLOR: '#eee',
SECONDARY_TEXT_COLOR: '#ccc',
PRIMARY_BORDER_COLOR: '#aaa'
}
export const lightTheme = {
mode: 'light',
PRIMARY_BACKGROUND_COLOR: '#D3CEC8',
SECONDARY_BACKGROUND_COLOR: '#E5DFD9',
TERTIARY_BACKGROUND_COLOR: '#C1BFBC',
PRIMARY_TEXT_COLOR: '#222',
SECONDARY_TEXT_COLOR: '#333',
PRIMARY_BORDER_COLOR: '#555'
}
You can make use of data attributes.
I have done the same in one my project like so :-
[data-color-mode="light"] {
--color-focus-ring: #7daee2;
--color-link-hover: #0039bd;
--color-primary-bg: #eef6ff;
--color-primary-text: #212121;
--color-primary-border: #98b2c9;
--color-secondary-bg: #c3d7f0;
--color-secondary-text: #1a1a1a;
}
[data-color-mode="dark"] {
--color-focus-ring: #5355d4;
--color-link-hover: #4183c4;
--color-primary-bg: #080808;
--color-primary-text: #f1f1f1;
--color-primary-border: #525252;
--color-secondary-bg: #191919;
--color-secondary-text: #d8d5d5;
}
You can add the attribute to your top-level element (assuming div) like so:-
<div className="appContainer" data-color-mode="light" ref={appRef}> ></div>
Now use that appRef to change the data-color-mode attribute as well update the localstorage in one function. Updating the data-color-mode allows you to toggle between css variable colors easily. In my code, I have done this the following way:-
const toggleColorMode = () => {
const nextMode = mode === "light" ? "dark" : "light";
// container is appRef.current only
container?.setAttribute("data-color-mode", nextMode);
setMode(nextMode);
};
I am not using redux for this. Simply React Context API is being used by me but it's doable in your scenario as well.
You can take more reference from the repo - https://github.com/lapstjup/animeccha/tree/main/src
Note - I think there are other routes where people go with CSS-IN-JS but I haven't explored them yet. This solution is one of the pure css ways.
Fun fact - Github has implemented their newest dark mode in a similar way and that's where I got the idea as well. You can inspect their page to see the same attribute name :D.

How to test CSS properties defined inside a class with react testing library

I am trying to test CSS properties that i have defined inside a class in css, wing the react testing library. However I am unable to do so.
Adding the simplified snippets.
import React from "react";
import { render, screen } from "#testing-library/react";
import '#testing-library/jest-dom/extend-expect';
import styled from "styled-components";
const Title = styled.span`
display: none;
background: red;
`
test("testRender", () => {
render(
<div>
<Title>Test</Title>
</div>
)
const spanElement = screen.getByText("Test");
const elementStyle = window.getComputedStyle(spanElement);
expect(elementStyle.display).toBe('none');
});
The test fails at the expect statement. I have tried refactoring to traditional css, there also the test fails. In both cases, I have tested it manually and the styles are taking effect.
I also understand that we should not directly test CSS properties, but I have tried testing the visibility with toBeVisible(), but that only works if the display: none is directly entered as a style, and not as part of a class.
This should be a very simple thing, that works out of the box, but I have been at it for some time now, without any luck.
Any help is appreciated.
I agree with #ourmaninamsterdam answer.
In addition, for checking appearance or disappearance of any element, you can also use .not.toBeInTheDocument like so:
expect(screen.queryByText("Test")).not.toBeInTheDocument();
NOTE: You must use queryByText instead of getByText in this case since queryByText wont throw an error if it doesn't find the element (it will return null).
Official docs Reference - https://testing-library.com/docs/guide-disappearance#nottobeinthedocument
You can use expect(screen.getByText("Test")).not.toBeVisible();
import React from "react";
import { render, screen } from "#testing-library/react";
import "#testing-library/jest-dom/extend-expect";
import styled from "styled-components";
it("does display", () => {
const Title = styled.span`
display: block;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).toBeVisible();
});
it("doesn't display", () => {
const Title = styled.span`
display: none;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).not.toBeVisible();
});
...see the sandbox: https://codesandbox.io/s/blazing-river-l6rn6?file=/App.test.js

Styling react-select with CSS modules works on Sandbox but not on local machine

The 'Using ClassNames' section of react-select docs states that using the className and classNamePrefix props
ensures compatibility with styled components, CSS modules and
other libraries.
In this CodeSandbox, with CSS modules and node-sass, it seems to work. However, if I replicate the following code on my local machine in a create-react-app, it doesn't work. My CRA uses the Typescript template. Is that the problem? Everything else is just the same.
Select.module.scss
.select {
outline: 1px solid red;
.select__control {
background-color: salmon;
}
}
Select.tsx
import React from 'react';
import RS from 'react-select';
import style from './Select.module.scss';
const options = [
{label: "hi", value: "hi"}
]
function Select(props: any) {
return (
<RS
options={options}
className={style.select}
classNamePrefix={style.select}
/>
)
}
export default Select;
App.tsx
import React from 'react';
import Select from './Select';
function App() {
return (
<div className="App">
<Select />
</div>
);
}
export default App;
I could make it work here by doing:
Select.module.scss
.select {
outline: 1px solid red;
[class$="-control"] {
background-color: salmon;
}
}
Select.tsx
import React from 'react';
import RS from 'react-select';
import style from './Select.module.scss';
const options = [
{label: "hi", value: "hi"}
]
function Select(props: any) {
return (
<RS
options={options}
className={style.select}
/>
)
}
export default Select;
Basically, I removed classNamePrefix from react-select component and changed .select__control to [class$="-control"], which matches all classes ending with -control.
The problem here was because css loader was adding a hash in my classnames eg {select: "styles_select__SQ71h", select__control: "styles_select__control__xcj2p"}.

Resources