I have a class component that I am trying to style the elements, the buttons, textboxes etc. To those ends I followed this link https://react-bootstrap.github.io/getting-started/introduction to install bootstrap in my react then i have import Button from 'react-bootstrap/Button'; and import 'bootstrap/dist/css/bootstrap.min.css'; in my header.
.
If I use <button type="submit">Submit</button> I notice that my button has no style at all and looking at examples I see everyone using <Button bsStyle="primary" bsSize="large" disabled>Test</Button> except that, when I do I get the error Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Since I am using a class component, does that mean I have to rewrite the entire thing to a function? But also I see the example on this link https://www.golangprograms.com/how-to-use-react-bootstrap-component.html using a class.
Appreciate if I be assisted in this regard.
Regards
import React, { Component } from 'react'
import Button from 'react-bootstrap/Button';
import 'bootstrap/dist/css/bootstrap.min.css';
class Transport extends Component {
constructor(props) {
super(props)
this.state = {
dieselTxt: '',
electricTxt: '',
gasolineTxt: '',
vehMaintain: '',
gasolineCarbon:''
}
}
handDieselChange = (event) => {
this.setState({
dieselTxt: event.target.value
})
}
handElectricChange = (event) => {
this.setState({
electricTxt: event.target.value
})
}
handGasTxtChange = (event) => {
this.setState({
gasolineTxt: event.target.value
})
}
handBusTxtChange = (event) => {
this.setState({
BusTxt: event.target.value
})
}
handTrainTxtChange = (event) => {
this.setState({
trainTxt: event.target.value
})
}
handFlightTxtChange = (event) => {
this.setState({
flightTxt: event.target.value
})
}
handVenSelectChange = (event) => {
this.setState({
vehMaintain: event.target.value
})
}
vehiclesCarbon = (event) => {
alert("test");
if (`${this.state.vehMaintain}` === '1') {
//` 22 / miles per galon(21.6) )* EF_passenger_vehicle*(nonCO2_vehicle_emissions_ratio)`
const estLBCarbonGas = ((this.state.gasolineTxt / 21.6) * 19.6* 1.01).toFixed(0);
this.setState({ gasolineCarbon: estLBCarbonGas })
}
event.preventDefault()
}
render() {
const { dieselTxt, electricTxt, gasolineTxt, vehMaintain, gasolineCarbon,trainTxt, BusTxt, flightTxt } = this.state
return (
<div>
<h4>Enter your vehicle's yearly milage</h4>
<form onSubmit={this.handleSubmit}>
<div>
<label>Gasoline </label>
<input type="text"
value={gasolineTxt}
onChange={this.handGasTxtChange}
/>
</div>
{/* <div>
<label>Diesel</label>
<input type="text"
value={dieselTxt}
onChange={this.handDieselChange}
/>
</div>
<div>
<label>Electric</label>
<input type="text"
value={electricTxt}
onChange={this.handElectricChange}
/>
</div> */}
<div>
<label>Do you perform regular maintenance on your vehicle?</label>
<select value={vehMaintain}
onChange={this.handVenSelectChange}>
<option value=""></option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
</div>
<div>
<input type="text"
value={gasolineCarbon}
/>
</div>
{/* <p>Public Transporation</p>
<div>
<label>Bus </label>
<input type="text"
value={BusTxt}
onChange={this.handBusTxtChange}
/>
</div>
<div>
<label>Train </label>
<input type="text"
value={trainTxt}
onChange={this.handTrainTxtChange}
/>
</div>
<p>Air Travel</p>
<div>
<label>Flights </label>
<input type="text"
value={flightTxt}
onChange={this.handFlightTxtChange}
/>
</div> */}
<div>
<button onClick={this.vehiclesCarbon}>Test</button>
<Button bsStyle="primary" bsSize="large" disabled>
Primary button
</Button>
</div>
</form>
</div>
)
}
}
export default Transport
Tab
import { useState } from "react";
import EnergyConsum from "./EnergyConsum";
import Transport from "./Transport";
import WasteForm from "./WasteForm";
//import "./App.css";
function Tabs() {
const [toggleState, setToggleState] = useState(1);
const toggleTab = (index) => {
setToggleState(index);
};
return (
<div className="container">
<div className="bloc-tabs">
<button
className={toggleState === 1 ? "tabs active-tabs" : "tabs"}
onClick={() => toggleTab(1)}
>
Energy Consumption
</button>
<button
className={toggleState === 2 ? "tabs active-tabs" : "tabs"}
onClick={() => toggleTab(2)}
>
Transport
</button>
<button
className={toggleState === 3 ? "tabs active-tabs" : "tabs"}
onClick={() => toggleTab(3)}
>
Tab 3
</button>
</div>
<div className="content-tabs">
<div
className={toggleState === 1 ? "content active-content" : "content"}
>
<h5>How much energy do you consume</h5>
<hr />
<EnergyConsum />
</div>
<div
className={toggleState === 2 ? "content active-content" : "content"}
>
<h2>How do you get around</h2>
<hr />
<Transport />
</div>
<div
className={toggleState === 3 ? "content active-content" : "content"}
>
<h2>Content 3</h2>
<hr />
<WasteForm />
</div>
</div>
</div>
);
}
export default Tabs;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Full Error Message
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
▶ 21 stack frames were collapsed.
Module.<anonymous>
H:/Documents/Projects/Solidity/MYCFC/my-cfc/src/index.js:8
5 | import reportWebVitals from './reportWebVitals';
6 |
7 |
> 8 | ReactDOM.render(
9 | <React.StrictMode>
10 | <App />
11 | </React.StrictMode>,
View compiled
Module../src/index.js
http://localhost:3001/static/js/main.chunk.js:2365:30
__webpack_require__
H:/Documents/Projects/Solidity/MYCFC/my-cfc/webpack/bootstrap:856
853 |
854 | __webpack_require__.$Refresh$.init();
855 | try {
> 856 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 857 | } finally {
858 | __webpack_require__.$Refresh$.cleanup(moduleId);
859 | }
View compiled
fn
H:/Documents/Projects/Solidity/MYCFC/my-cfc/webpack/bootstrap:150
147 | );
148 | hotCurrentParents = [];
149 | }
> 150 | return __webpack_require__(request);
| ^ 151 | };
152 | var ObjectFactory = function ObjectFactory(name) {
153 | return {
View compiled
1
http://localhost:3001/static/js/main.chunk.js:2501:18
__webpack_require__
H:/Documents/Projects/Solidity/MYCFC/my-cfc/webpack/bootstrap:856
853 |
854 | __webpack_require__.$Refresh$.init();
855 | try {
> 856 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 857 | } finally {
858 | __webpack_require__.$Refresh$.cleanup(moduleId);
859 | }
View compiled
checkDeferredModules
H:/Documents/Projects/Solidity/MYCFC/my-cfc/webpack/bootstrap:45
42 | }
43 | if(fulfilled) {
44 | deferredModules.splice(i--, 1);
> 45 | result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
| ^ 46 | }
47 | }
48 |
View compiled
Array.webpackJsonpCallback [as push]
H:/Documents/Projects/Solidity/MYCFC/my-cfc/webpack/bootstrap:32
29 | deferredModules.push.apply(deferredModules, executeModules || []);
30 |
31 | // run deferred modules when all chunks ready
> 32 | return checkDeferredModules();
| ^ 33 | };
34 | function checkDeferredModules() {
35 | var result;
View compiled
(anonymous function)
http://localhost:3001/static/js/main.chunk.js:1:65
Related
Actually I wanna create slider with dots, slider is working, but dots are hidden. How should I make dots visible while using react swipper slider.
I am using styled components for css. The thing is, I cannot find what is false in this part of code. please help me to figure out with this problem.
I tried to make my slider dots visible, however they are not showing.
this is my code
import { Pagination, Navigation, Scrollbar, A11y } from 'swiper';
import { Images } from 'assets/images';
import { useWindowDimensions } from 'hooks/useWindowDimensions';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from 'utils/routeNames';
import { Swiper, SwiperSlide } from 'swiper/react';
// Import Swiper styles
import 'swiper/swiper.scss';
import {
CardAndDescriptionBlock,
CardBlock,
CountryImage,
TripDurationAndPrice,
TripDuration,
CardDescription,
TripCountryAndPrice,
CountryStarsPriceWrapper,
TripCountryAndStars,
TripPrice,
PricePerPerson,
TripCountry,
ReadMore,
DescriptionContainer,
} from './styled';
export const HotOffersCarousel = ({ hotOffers }) => {
const navigate = useNavigate();
const { width } = useWindowDimensions();
const navigateToTour = (id) => {
navigate(`${ROUTES.HOT_TOURS}/${id}`);
};
return (
<Swiper
slidesPerView={width < 768 ? 2 : 1}
spaceBetween={10}
slidesPerGroup={width < 768 ? 2 : 1}
loop={true}
pagination={{
dynamicBullets: true,
}}
modules={[Pagination, Navigation, Scrollbar, A11y]}
className="mySwiper"
>
{hotOffers?.map((item) => (
<SwiperSlide key={item.id}>
<CardAndDescriptionBlock>
<CardBlock>
<CountryImage background={item?.main_image}>
<TripDurationAndPrice>
<TripDuration>
{item?.stay_days} Days / {item?.stay_nights} nights
</TripDuration>
<PricePerPerson> $ {item?.price}/Person </PricePerPerson>
</TripDurationAndPrice>
</CountryImage>
<TripCountryAndPrice>
<CountryStarsPriceWrapper>
<TripCountryAndStars>
<TripCountry> {item?.title} </TripCountry>
<img src={Images.stars} />
</TripCountryAndStars>
<TripPrice>$ {item?.price} </TripPrice>
</CountryStarsPriceWrapper>
<DescriptionContainer
isMedia
dangerouslySetInnerHTML={{ __html: item.description }}
/>
<ReadMore onClick={() => navigateToTour(item?.id)} isMedia>
Read More <img src={Images.mainColorRightArrow} />
</ReadMore>
</TripCountryAndPrice>
</CardBlock>
<CardDescription>
<TripCountryAndStars>
<TripCountry> Venice Italy </TripCountry>
<img src={Images.stars} />
</TripCountryAndStars>
<DescriptionContainer
dangerouslySetInnerHTML={{ __html: item.description }}
/>
<ReadMore onClick={() => navigateToTour(item?.id)}>
Read More <img src={Images.mainColorRightArrow} />
</ReadMore>
</CardDescription>
</CardAndDescriptionBlock>
</SwiperSlide>
))}
</Swiper>
);
};
Im trying to create a Pizza delivery app with React and next.js. What I'm stuck with is the photos of the pizzas I have in the sanity backend won't render to the app. I can see the json array for the 6 pizzas in the terminal and also the console after i connect the backend. I've been stuck on this all day and appreciate any help. Is there a different way to pass pizzas to the Home function in the index.js? :)
The exact error is below aswell.
error - components\Menu.jsx (17:27) # eval
TypeError: (0 , _lib_client__WEBPACK_IMPORTED_MODULE_1__.default) is not a function
15 | {/* pizzas */}
16 | {pizzas.map((pizza, id) => {
> 17 | const src = urlFor(pizza.image);
| ^
18 | console.log(pizza.image);
19 | return (
20 | <div className={css.pizza} key={id}>
Index.js
import Layout from '../components/layout';
import Hero from '../components/Hero';
import css from '../styles/Home.module.css';
import Services from '../components/Services';
import { client } from '../lib/client';
import Menu from '../components/Menu';
export default function Home({ pizzas }) {
return (
<Layout>
<div className={css.container}>
<Head>
<title>FUDO</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/Logo.png" />
</Head>
{/* body */}
<main>
<Hero />
<Services />
<Menu pizzas={pizzas} />
</main>
</div>
</Layout>
);
}
export const getServerSideProps = async () => {
const query = '*[_type == "pizza"]';
const pizzas = await client.fetch(query);
console.log(pizzas);
return {
props: {
pizzas,
},
};
};
Menu.jsx
import urlFor from '../lib/client';
import Image from 'next/image';
export default function Menu({ pizzas }) {
console.log(pizzas);
return (
<div className={css.container}>
<div className={css.heading}>
<span>OUR MENU</span>
<span>Menu That Always</span>
<span>Make You Fall In Love</span>
</div>
{/* pizzas */}
{pizzas.map((pizza, id) => {
const src = urlFor(pizza.image);
console.log(pizza.image);
return (
<div className={css.pizza} key={id}>
<div className={css.ImageWrapper}>
<Image
loader={() => src}
src={src}
alt=""
objectFit="cover"
layout="fill"
/>
</div>
</div>
);
})}
</div>
);
}
Client.js
import SanityClient from '#sanity/client';
import ImageUrlBuilder from '#sanity/image-url';
export const client = SanityClient({
projectId: 'exiz0rgv',
dataset: 'production',
apiVersion: '2022-09-01',
useCdn: true,
token:
'skT82oCId91vDPWOQoLVx6qVxX3mLxGYzSQeX0tsRRS2KGDFtmWXuIRxz0yyz3RyErMeUHraDpTDTLbWgjoiLcnh4GoL3CChOcNpkGFzQeywcAR73yQiqnxjBlL3Z435QgzTZJEEZJnI7O0R4RdQaCivBTKKIBV79efdtavbNvcfx9iSB2nS',
});
const builder = ImageUrlBuilder(client);
export const urlFor = (source) => builder.image(source);
In this project I am using FireBase database. I need to change the number of users per page for example 5, Change the number of pages according to the total number of users / number of users per page. To do this, I change the query params, but it does not want to change. I don't know how to enter the parameters correctly so that they appear to me as they should, maybe I didn't write them correctly or I need to write them differently
import React, {Component} from "react";
import classes from "./users.module.css";
import * as axios from "axios";
import userPhoto from "../../assect/image/standartAvatar.jpg";
class Users extends Component {
componentDidMount() {
axios
.get(
`https://kabzda-cff30-default-rtdb.europe-west1.firebasedatabase.app/users.json?page=${this.props.currentPage}&count=${this.props.pageSize}`
)
.then((response) => {
this.props.setUsers(response.data.items);
this.props.setTotalUsersCount(response.data.totalCount);
})
}
onPageChanged = (pageNumber) => {
this.props.setCurrentPage(pageNumber)
axios
.get(
`https://kabzda-cff30-default-rtdb.europe-west1.firebasedatabase.app/users.json?page=${pageNumber}&count=${this.props.pageSize}`
)
.then((response) => {
this.props.setUsers(response.data.items);
})
}
render() {
let pagesCount = Math.ceil(this.props.totalUsersCount / this.props.pageSize)
let pages = [];
for(let i = 1; i <= pagesCount; i++){
pages.push(i)
}
return (
<div>
<div className={classes.counter}>
{pages.map(p => (
<span className={(this.props.currentPage === p && classes.selectedPage) || classes.pointer}
onClick={() => {this.onPageChanged(p)}}
>
| {p} |</span>
))}
</div>
{this.props.users.map((u, i) => (
<div key={i+1}>
<span>
<div>
<img
src={u.photos.small !== "" ? u.photos.small : userPhoto}
className={classes.userPhoto}
alt="avatar"
/>
</div>
<div>
{u.followed ? (
<button
onClick={() => {
this.props.unfollow(u.id);
}}
>
UnFollow
</button>
) : (
<button
onClick={() => {
this.props.follow(u.id);
}}
>
Follow
</button>
)}
</div>
</span>
<span>
<span>
<div>{u.name}</div>
<div>{u.status}</div>
</span>
<span>
<div>{"u.location.country"}</div>
<div>{"u.location.city"}</div>
</span>
</span>
</div>
))}
</div>
);
}
}
export default Users;
I've been trying to render {ingredients} with line breaks, each time the user presses Enter and keys in another ingredient. I've been getting all the user's inputs in one line e.g. grapeonionlettuce I'm not sure what, where or how to add code so that it'll have line breaks - tried using CSS too, by referencing the className return-ingredients-list and using white-space etc. but to no avail. Please help, thanks in advance, if possible.
//import { useState} from "react";
//import {Paper} from "#material-ui/core";
const {useState} = React;
const CRBUploadRecipe = () => {
const [recipeName, setRecipeName] = useState("");
const [selectedFile, setSelectedFile] = useState(undefined);
const [ingredients, setIngredients] = useState([]);
const handleEnterKeyPress = (e) => {
if(e.which === 13) {
const input = document.getElementById("ingredients");
setIngredients([input.value, ...ingredients])
console.log(ingredients)
}
};
return (
<div>
{/*<Paper elevation={12}>*/}
<div className="upload-recipe">
<form>
<label htmlFor="form-title" className="form-title">
Share to the Community <br/>
<input id="recipe-name" type="text" value={recipeName} placeholder="Recipe name"
onChange={e => setRecipeName(e.target.value)}
/>
</label>
<label htmlFor="upload-image" className="upload-image">
Upload image <br/>
<input id="upload-image" type="file" value={selectedFile}
onChange={e => setSelectedFile(e.target.files[0])}
/>
</label>
<label htmlFor="ingredients" className="ingredients">
Ingredients <br/>
<input id="ingredients" type="text" placeholder="Write ingredients"
onKeyPress={handleEnterKeyPress} />
</label>
<div className="return-ingredients-list">
{ingredients}
</div>
</form>
</div>
{/*</Paper>*/}
</div>
);
};
ReactDOM.render(
<div>
DEMO
<CRBUploadRecipe />
</div>,
document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />
<div id="ingredients"></div>
first of all don't use document.getElementById("ingredients") in react app.
second of all you can put each ingredient in paragraph or div;
import { useState} from "react";
import {Paper} from "#material-ui/core";
const CRBUploadRecipe = () => {
const [recipeName, setRecipeName] = useState("");
const [selectedFile, setSelectedFile] = useState(undefined);
const [ingredients, setIngredients] = useState([]);
const handleEnterKeyPress = (e) => {
if(e.which === 13) {
const input = e.target; // your handler already has access to input;
setIngredients((prev) => [input.value, ...prev])
console.log(ingredients)
}
}
return (
<Paper elevation={12}>
<div className="upload-recipe">
<form>
<label htmlFor="form-title" className="form-title">
Share to the Community <br/>
<input id="recipe-name" type="text" value={recipeName} placeholder="Recipe name"
onChange={e => setRecipeName(e.target.value)}
/>
</label>
<label htmlFor="upload-image" className="upload-image">
Upload image <br/>
<input id="upload-image" type="file" value={selectedFile}
onChange={e => setSelectedFile(e.target.files[0])}
/>
</label>
<label htmlFor="ingredients" className="ingredients">
Ingredients <br/>
<input id="ingredients" type="text" placeholder="Write ingredients"
onKeyPress={handleEnterKeyPress} />
</label>
<div className="return-ingredients-list">
{ingredients.map((ingridient, id) => (<p key={id}>{ingridient}</p>)}
</div>
</form>
</div>
</Paper>
);
}
export default CRBUploadRecipe;
I'm JS newbie making a website :)
When I scroll down from main page,
I want to make it move to each component(Comp1,Comp2..) right away.
But I don't know what to do..
Can you tell me what to look for?
I wrote the react code as below.
import React from 'react'
import {Header} from 'components/Header'
import {Title} from 'style/CommonStyle';
const Comp1 = () => {
return (
<div>
<Title>Title of Comp1</Title>
...
</div>
)
}
const Comp2 = () => {
return (
<div>
<Title>Title of Comp1</Title>
...
</div>
)
}
const MainPage = () => {
return (
<div>
<Header />
<Comp1 />
<Comp2 />
</div>
)
}
export default MainPage