Setting Attributes for Components in React not working - css

I'm following a video course on React, and it is showing us the basics of creating a shopping cart that will eventually look something like this:
I am still early in the course. I am building a component and setting the attributes. Right now, it should just show "Zero" and have the word "Increment" on the button. The problem is, I cannot see the word "Zero" in the Chrome browser. Chrome shows that the word is there, though:
Here is my React code for counter.jsx:
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
class Counter extends Component {
state = {
count: 0
};
styles = {
fontSize: 30,
fontWeight: 'bold',
};
render() {
return (
<div>
<span style={this.styles} className='badge badge-primary m-2'>{this.formatCount()}</span>
<button className='btn btn-secondary btn-sm'>Increment</button>
</div>
);
}
formatCount() {
const { count } = this.state;
return count === 0 ? 'Zero' : count;
}
}
export default Counter;
It is called in index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Counter />
</React.StrictMode>
);
The course has a forum, and I asked a question about this yesterday >> HERE <<, but there has been no answer, and I cannot continue building the project with the 1st step not working.
Can someone point out what it is that I did wrong?
Also, I personally think that the formatCount() function should declare count as:
formatCount() {
const { count } = this.state.count;
return count === 0 ? 'Zero' : count;
}
But, that makes it so that the text "Zero" no longer appears in the Chrome debugger. Why?
(I included the bootstrap tag because the index page uses bootstrap, and it could be doing something that is hiding my text)

Related

Next js and Next Auth overlapping react declarations

I am running Next js and Next Auth in multiple project, and all of a sudden all of them decided to crash with the same error.
Module parse failed: Identifier '_react' has already been declared (14:6)
File was processed with these loaders:
* ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
You may need an additional loader to handle the result of these loaders.
| const _material = require("#mui/material");
| const _xDataGrid = require("#mui/x-data-grid");
> const _react = require("next-auth/react");
| const _reportTable = /*#__PURE__*/
a simple example that crashes looks like this...
As you can see from the example below. I am not importing react twice.
import React from "react";
import { Box } from "#mui/material";
import { DataGrid, GridColDef, GridRowsProp } from "#mui/x-data-grid";
import { getSession } from "next-auth/react";
import ReportTable from "../src/components/ReportTable";
export default function Home() {
const findSession = () => {
const session = getSession();
console.log(session);
return session;
};
return (
<Box>
<ReportTable title="Price Books">
<DataGrid
sx={{ border: "0" }}
rows={rows}
columns={columns}
headerHeight={40}
/>
</ReportTable>
</Box>
);
}
If I remove the getSession import at the top everything runs fine. The other developers on my team can run these project just fine, so I believe it's an environmental issue on my side.
Has anyone else run into this issue?
I have built the project and it works fine. The errors only occur in my dev environment.
I also cloned the repo on my personal machine and it worked fine there as well.
The problem was with a new plugin that came out today, "Code Ninja". If you are facing this issue, disable that VSCode extension.

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.

is it possible Customise FullCalendar with css in react?

I just begin with FullCalendar , i'm implementing it in a react project , everything good now but i want to customize the actual calendar , iwant it to respect my customer need.
My question : is it possible to add a classname to the FullCalendar component like this :
( i tried but i can't reach the classname in my css file )
<FullCalendar
className= "FullCalendarMonthClient"
defaultView= "dayGridMonth"
plugins={[dayGridPlugin]}
columnHeaderFormat= {{
weekday: "long"
}}
locale="fr"
events={[
{ title: 'event 1', start: '2019-12-06', end: '2019-12-07' },
{ title: 'event 1', start: '2019-12-06', end: '2019-12-07' }
]}
/>
and after use it to customize my calendar with css. I use on the same page an other calendar , a DayView that why i ask to put a classname in my component so i can style my dayview/monthview without touching the Monthview. Or how can i create my own theme ?
Thanks comunity
You can create a styled wrapper that will overwrite the internal styles.
import FullCalendar from "#fullcalendar/react";
import styled from "#emotion/styled";
export const StyleWrapper = styled.div`
.fc td {
background: red;
}
`
const MyApp = ()=> {
return (
<StyleWrapper>
<FullCalendar/>
</StyleWrapper>
);
}
Indeed, a styled wrapper works. For example, try changing the buttons (next, prev) in the Calendar:
import FullCalendar from "#fullcalendar/react";
import timeGridPlugin from '#fullcalendar/timegrid';
// needed for the style wrapper
import styled from "#emotion/styled";
// add styles as css
export const StyleWrapper = styled.div`
.fc-button.fc-prev-button, .fc-button.fc-next-button, .fc-button.fc-button-primary{
background: red;
background-image: none;
}
`
// component with calendar, surround the calendar with the StyleWrapper
function Schedule({ ...props }) {
return (
<StyleWrapper>
<FullCalendar ... />
</StyleWrapper>
);
}
export default Schedule;
If you happen to be using #fullcalendar/react with #fullcalendar/bootstrap and #fullcalendar/rrule YOU NEED TO CHECK YOUR IMPORTS.
I have having an issue where the rrulePlugin was over-riding my bootstrap theme, It was the way I was importing.
Import in this order solved it for me
import React from 'react';
import {Card, CardBody, CardHeader, Col, Row} from 'reactstrap';
import FullCalendar from '#fullcalendar/react';
import dayGridPlugin from '#fullcalendar/daygrid';
import interactionPlugin from '#fullcalendar/interaction';
import timeGridPlugin from '#fullcalendar/timegrid';
import listPlugin from '#fullcalendar/list';
import rrulePlugin from '#fullcalendar/rrule';
import bootstrapPlugin from '#fullcalendar/bootstrap';
<div>
<CardBody className="p-0">
<FullCalendar
ref={calendarRef}
headerToolbar={false}
plugins={[ // plugins MUST be in this order for mine to work or else I get errors
rrulePlugin,
dayGridPlugin,
bootstrapPlugin,
timeGridPlugin,
interactionPlugin,
listPlugin,
]}
initialView="dayGridMonth"
themeSystem="bootstrap"
dayMaxEvents={2}
height={800}
stickyHeaderDates={false}
editable
selectable
selectMirror
select={info => {
console.log("calendarInfo", info.start.toISOString())
if(info.start < moment().subtract(1, 'day')) {
toast(
<Fragment>
<strong>Select Future date</strong>
</Fragment>
);
} else if(isCompose) {
return (calendarView === "Month View" ? setShowTimeModal(!showTimeModal) : ""),
setAddScheduleStartDate(info.start.toString())
} else {
setAddScheduleStartDate(info.start.toISOString());
setIsOpenScheduleModal(true);
}
}}
views={views}
eventTimeFormat={eventTimeFormat}
eventClick={handleEventClick}
events={calendar}
buttonText={buttonText}
eventDrop={(e) => { return console.log("eventDrop ran======-----======", dispatch(calendarUpdate({start: e.event.start, end: e.event.end, _id: e.event._def.extendedProps._id})))}}
/>
</CardBody>
</div>

Dynamically load .css based on condition in reactJS application

I have a reactJS application that I want to make available to multiple clients. Each clients has unique color schemes. I need to be able to import the .css file that corresponds to the specific client.
For example, if client 1 logs into the application, I want to import client1.css. if client 2 logs into the application, I want to import client2.css. I will know the client number once I have validated the login information.
The application contains multiple .js files. Every .js file contains the following at the top of the file
import React from 'react';
import { Redirect } from 'react-router-dom';
import {mqRequest} from '../functions/commonFunctions.js';
import '../styles/app.css';
Is there a way to import .css files dynamically for this scenario as opposed to specifying the .css file in the above import statement?
Thank you
Easy - i've delt with similar before.
componentWillMount() {
if(this.props.css1 === true) {
require('style1.css');
} else {
require('style2.css');
}
}
Consider using a cssInJs solution. Popular libraries are: emotion and styled-components but there are others as well.
I generally recommend a cssInJs solution, but for what you are trying to do it is especially useful.
In Emotion for example they have a tool specifically build for this purpose - the contextTheme.
What cssInJs basically means is that instead of using different static css files, use all the power of Javascript, to generate the needed css rules from your javascript code.
A bit late to the party, I want to expand on #Harmenx answer.
require works in development environments only, once it goes to production you're likely to get errors or not see the css file at all. Here are some options if you, or others, encounter this:
Option 1: Using css modules, assign a variable of styles with the response from the import based on the condition.
let styles;
if(this.props.css1 === true) {
//require('style1.css');
import("./style1.module.css").then((res) => { styles = res;});
} else {
//require('style2.css');
import("./style2.module.css").then((res) => { styles = res;});
}
...
<div className={styles.divClass}>...</div>
...
Option 2: using Suspend and lazy load from react
// STEP 1: create components for each stylesheet
// styles1.js
import React from "react";
import "./styles1.css";
export const Style1Variables = (React.FC = () => <></>);
export default Style1Variables ;
// styles2.js
import React from "react";
import "./styles2.css";
export const Style2Variables = (React.FC = () => <></>);
export default Style2Variables ;
// STEP 2: setup your conditional rendering component
import React, {lazy, Suspense} from "react";
const Styles1= lazy(() => import("./styles1"));
const Styles2= lazy(() => import("./styles2"));
export const ThemeSelector = ({ children }) => {
return (
<>
<Suspense fallback={null} />}>
{isClient1() ? <Styles1 /> : <Styles2/>}
</Suspense>
{children}
</>
);
};
// STEP 3: Wrap your app
ReactDOM.render(
<ThemeSelector>
<App />
</ThemeSelector>,
document.getElementById('root')
);
Option 3: Use React Helm which will include a link to the stylesheet in the header based on a conditional
class App extends Component {
render() {
<>
<Helmet>
<link
type="text/css"
rel="stylesheet"
href={isClient1() ? "./styles1.css" : "./styles2.css"}
/>
</Helmet>
...
</>
}
}
Personally, I like option 2 because you can set a variable whichClientIsThis() then modify the code to:
import React, {lazy, Suspense} from "react";
let clientID = whichClientIsThis();
const Styles= lazy(() => import("./`${clientID}`.css")); // change your variable filenames to match the client id.
export const ThemeSelector = ({ children }) => {
return (
<>
<Suspense fallback={null} />}>
<Styles />
</Suspense>
{children}
</>
);
};
ReactDOM.render(
<ThemeSelector>
<App />
</ThemeSelector>,
document.getElementById('root')
);
This way you don't need any conditionals. I'd still recommend lazy loading and suspending so the app has time to get the id and make the "decision" on which stylesheet to bring in.

How to change the properties of a Blaze Template inside a React Component

I'm using the Accounts UI meteor package in my React + Meteor project and want to render the loginButtons template with the property align="right". In Blaze the code would just be {{> loginButtons align="right"}}, but I'm at at a loss with how to add this property in React.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Template } from 'meteor/templating';
import { Blaze } from 'meteor/blaze';
export default class AccountsUIContainer extends Component {
componentDidMount() {
this.view = Blaze.render(Template.loginButtons, // How do I give loginButtons `align="right`?
ReactDOM.findDOMNode(this.refs.container));
}
componentWillUnmount() {
Blaze.remove(this.view);
}
render() {
return <span ref="container" />;
}
}
I think Blaze.renderWithData() may be part of the solution, but my tests with this method haven't worked so far. I also think people have created solutions to using Blaze templates in React before, but I'm not sure these alternate solutions would be the "right" way to solve this problem in Meteor 1.4.
The answer was right inside the documentation. First meteor add gadicc:blaze-react-component, then in the component
import React from 'react';
import Blaze from 'meteor/gadicc:blaze-react-component';
const App = () => (
<div>
<Blaze template="loginButtons" align="right" />
</div>
);

Resources