I just added a swiper to my React project, and I need the pagination background to be transparent. The modifications I make on the CSS file don't seem to have any effect on the page itself.
So the first part is my JSX file, and the second is my CSS file. Both are linked correctly, I tried modifying the minified file but the problem remains the same.
import React, { useEffect, useState } from 'react';
import Game from '../Game';
import axios from 'axios';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper';
import 'swiper/swiper-bundle.css';
import { Keyboard, Pagination, A11y } from 'swiper';
const GamesList = (props) => {
const { searchValue, setGameId, gameId, platform, genre } = props;
const [data, setData] = useState([]);
useEffect(() => {
const timeout = setTimeout(() => {
axios
.get(
`https://api.rawg.io/api/games?key=453247c1c78a4a88aa6594a59227801b&genres=${genre}&platforms=${platform}&search=${searchValue}`
)
.then((res) => {
setData(res.data.results);
});
}, 700);
return () => clearTimeout(timeout);
}, [searchValue, platform, genre]);
return (
<div id='list'>
{/* <p>{platformName}</p> */}
<Swiper
modules={[Navigation, A11y, Keyboard, Pagination]}
pagination
navigation
a11y
keyboard
effect
speed={800}
slidesPerView={3}
loop
className='my-swiper'
>
{data
.filter((gameChoice) => gameChoice.name.toLowerCase())
.map((game, index) => (
<SwiperSlide>
<Game/>
</SwiperSlide>
))}
</Swiper>
</div>
);
};
export default GamesList;
I tried adding the "background: none" line but nothing happened...
.swiper-pagination {
position: absolute;
text-align: center;
transition: 300ms opacity;
transform: translate3d(0, 0, 0);
z-index: 10;
background: none;
}
I am working on a web based project. All code is executed but the styles are not being applied to files. Below is code of my react file. I also added my css file below it.
I tried using .sass extension which is also not working.
Can anyone help me with it? How do I apply styles?
import "./App.css";
import React, {useState, useEffect} from "react";
import Axios from "axios";
function App(){
const [searchVal,setSearchVal]=useState('');
//getting values from DB
return <div>
<input type="text" placeholder="Search College" onChange={event =>{setSearchVal(event.target.value)}}></input>
{collegeList.filter((val)=>{
if(searchVal==""){
return val;
}else if (val.Name_of_College.toLowerCase().includes(searchVal.toLowerCase())){
return val;
}
}).map((val)=>{
return <div className="clgListDiv" > <p>
College Name: {val.Name_of_College} <br></br>
</p>
</div>
})}
</div>
}
export default App;
This is the css file
.App{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
.APP input{
margin-top: 20px;
width:350px;
height: 40px;
font-size: 20px;
padding-left: 10px;
}
Well it doesn't work because you didn't add className attribute in JSX code in first div and maybe you should rename .APP input to .App input in your CSS file as you also want same styling in input tag also.
import "./App.css";
import React, {useState, useEffect} from "react";
import Axios from "axios";
function App(){
const [searchVal,setSearchVal]=useState('');
//getting values from DB
return <div className='App'>
<input type="text" placeholder="Search College" onChange={event =>{setSearchVal(event.target.value)}}></input>
{collegeList.filter((val)=>{
if(searchVal==""){
return val;
}else if (val.Name_of_College.toLowerCase().includes(searchVal.toLowerCase())){
return val;
}
}).map((val)=>{
return <div className="clgListDiv" > <p>
College Name: {val.Name_of_College} <br></br>
</p>
</div>
})}
</div>
}
export default App;
Best Practice in React:
import React, { useState, useEffect } from "react";
import "./App.css";
import Axios from "axios";
function App() {
const [searchVal, setSearchVal] = useState("");
//getting values from DB
const content = collegeList
.filter((val) => {
if (searchVal == "") {
return val;
} else if (
val.Name_of_College.toLowerCase().includes(searchVal.toLowerCase())
) {
return val;
}
})
.map((val) => {
return (
<div className="clgListDiv">
<p>
College Name: {val.Name_of_College} <br></br>
</p>
</div>
);
});
return (
<div>
<input
type="text"
placeholder="Search College"
onChange={(event) => {
setSearchVal(event.target.value);
}}
></input>
{content}
</div>
);
}
export default App;
I am trying to align the cards horizontally and it worked fine before, but after I pulled the data from the API and used for-loop to show the data in the browser the cards stacked vertically.
Here is the javascript code
import React, { useEffect, useState } from "react";
import "./Home.css";
import axios from "axios";
function Home() {
const [ApiData, setApiData] = useState([]);
useEffect(() => {
async function getData() {
const data = await axios.get("http://127.0.0.1:8000/?format=json");
console.log(data.data);
setApiData(data.data.Product);
return data;
}
getData();
}, []);
return (
<>
{ApiData.map((obj, index) => {
let x;
for (x in obj) {
return (
<div className="container">
<div className="card">
{/* <img className="store-img" src={obj.image} alt="" /> */}
<span>{obj.name}</span>
</div>
</div>
);
}
})}
</>
);
}
export default Home;
Here is the CSS
.container {
display: flex;
flex-direction: row;
flex: 1;
}
.card {
display: flex;
flex-direction: row;
margin: 10px 50px 10px 50px;
justify-content: center;
align-items: baseline;
flex: 1;
height: 16em;
width: 12em;
max-height: 18em;
max-width: 16em;
border-radius: 4px;
box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
}
.store-img {
height: 100%;
width: 100%;
}
The JSON File which I am using for this code
You are creating a new div with class container in every loop iteration. Put loop inside container div.
import React, { useEffect, useState } from "react";
import "./Home.css";
import axios from "axios";
function Home() {
const [ApiData, setApiData] = useState([]);
useEffect(() => {
async function getData() {
const data = await axios.get("http://127.0.0.1:8000/?format=json");
console.log(data.data);
setApiData(data.data.Product);
return data;
}
getData();
}, []);
return (
<div className="container">
{ApiData.map((obj, index) => {
let x;
for (x in obj) {
return (
<div className="card">
{/* <img className="store-img" src={obj.image} alt="" /> */}
<span>{obj.name}</span>
</div>
);
}
})}
</div>
);
}
export default Home;
Wrap your divs with class d-flex if you are using bootstrap or create a class with property display: flex. Try below code :
import React, { useEffect, useState } from "react";
import "./Home.css";
import axios from "axios";
function Home() {
const [ApiData, setApiData] = useState([]);
useEffect(() => {
async function getData() {
const data = await axios.get("http://127.0.0.1:8000/?format=json");
console.log(data.data);
setApiData(data.data.Product);
return data;
}
getData();
}, []);
return (
<div className="d-flex">
{ApiData.map((obj, index) => {
let x;
for (x in obj) {
return (
<div className="container" key={index}>
<div className="card">
{/* <img className="store-img" src={obj.image} alt="" /> */}
<span>{obj.name}</span>
</div>
</div>
);
}
})}
</div>
);
}
export default Home;
I'm sure this has been asked before however, I can't find the answer. How do you get the Nav menu to close when you click on a NavLink in reactstrap or is this still in development?
Reactstrap has an isOpen parameter in state, so you need to set it to false
constructor(props) {
super(props);
this.closeNavbar = this.closeNavbar.bind(this);
this.state = {
isOpen: false
};
}
closeNavbar() {
this.setState({
isOpen: false
});
}
// and in Link or a element add onClick handler like this
<Link to="/" onClick={closeNavbar}>Home</Link>
Here is the code I use:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import library from './FontAwesomeLibrary';
import logo from '../../assets/images/logo.svg';
import {
Collapse,
Navbar,
NavbarToggler,
Nav,
NavItem } from 'reactstrap';
class Topbar extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.closeNavbar = this.closeNavbar.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
this.state = {
isOpen: false,
};
}
componentWillMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
closeNavbar() {
this.setState({
isOpen: false
});
}
handleClickOutside(event) {
const t = event.target;
if (this.state.isOpen && !t.classList.contains('navbar-toggler')) {
this.closeNavbar();
}
}
render() {
return (
<div className="topbar">
<section className="container">
<Navbar color="light" className="header" expand="md">
<Link className="locoLink" to="/"><img src={logo} className="logo" alt="logo" /></Link>
<Link to="/" className="logoCompany">Redux Blog</Link>
<NavbarToggler onClick={this.toggle}>
<FontAwesomeIcon icon={this.state.isOpen ? "times" : "bars"}/>
</NavbarToggler>
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto routes" navbar>
<NavItem>
<Link to="/" onClick={this.closeNavbar}>Posts</Link>
</NavItem>
<NavItem>
<Link to="/posts/new" onClick={this.closeNavbar}>New Post</Link>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</section>
</div>
);
}
}
export default Topbar;
It also handles outside clicks.
FontAwesomeLibrary
import { library } from '#fortawesome/fontawesome-svg-core';
import { faCoffee } from '#fortawesome/free-solid-svg-icons';
import { faMugHot } from '#fortawesome/free-solid-svg-icons';
import { faTimes } from '#fortawesome/free-solid-svg-icons';
import { faBars } from '#fortawesome/free-solid-svg-icons';
import { faChevronUp } from '#fortawesome/free-solid-svg-icons';
library.add(faCoffee);
library.add(faMugHot);
library.add(faTimes);
library.add(faBars);
library.add(faChevronUp);
export default library;
I created FontAwesomeLibrary according to
https://fontawesome.com/how-to-use/on-the-web/using-with/react
This is an issue with routing. On a normal webpage a link in a bootstrap nav would cause a new page to load with the nav now closed. Since react doesn't reload the page the nav remains open. In order to fix this you'll need to add the following to each of your <Link> elements in the nav: onClick={this.toggleNavbar}.
I can't get correct value into the store when trying to upload a file. Instead of file content, I get something like { 0: {} }.
Here's the code:
const renderInput = field => (
<div>
<input {...field.input} type={field.type}/>
{
field.meta.touched &&
field.meta.error &&
<span className={styles.error}>{field.meta.error}</span>
}
</div>
);
render() {
...
<form className={styles.form} onSubmit={handleSubmit(submit)}>
<div className={styles.interface}>
<label>userpic</label>
<Field
name="userpic"
component={renderInput}
type="file"
/>
</div>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<div>
</form>
...
}
All the examples on the web that I found were made using v5 of redux-form.
How do I do file input in redux-form v6?
Create a Field Component like:
import React, {Component} from 'react'
export default class FieldFileInput extends Component{
constructor(props) {
super(props)
this.onChange = this.onChange.bind(this)
}
onChange(e) {
const { input: { onChange } } = this.props
onChange(e.target.files[0])
}
render(){
const { input: { value } } = this.props
const {input,label, required, meta, } = this.props //whatever props you send to the component from redux-form Field
return(
<div><label>{label}</label>
<div>
<input
type='file'
accept='.jpg, .png, .jpeg'
onChange={this.onChange}
/>
</div>
</div>
)
}
}
Pass this component to the Field component where you needed. No need of additional Dropzone or other libraries if you are after a simple file upload functionality.
My example of redux form input wrapper with Dropzone
import React, {Component, PropTypes} from 'react';
import Dropzone from 'react-dropzone';
import { Form } from 'elements';
import { Field } from 'redux-form';
class FileInput extends Component {
static propTypes = {
dropzone_options: PropTypes.object,
meta: PropTypes.object,
label: PropTypes.string,
classNameLabel: PropTypes.string,
input: PropTypes.object,
className: PropTypes.string,
children: PropTypes.node,
cbFunction: PropTypes.func,
};
static defaultProps = {
className: '',
cbFunction: () => {},
};
render() {
const { className, input: { onChange }, dropzone_options, meta: { error, touched }, label, classNameLabel, children, name, cbFunction } = this.props;
return (
<div className={`${className}` + (error && touched ? ' has-error ' : '')}>
{label && <p className={classNameLabel || ''}>{label}</p>}
<Dropzone
{...dropzone_options}
onDrop={(f) => {
cbFunction(f);
return onChange(f);
}}
className="dropzone-input"
name={name}
>
{children}
</Dropzone>
{error && touched ? error : ''}
</div>
);
}
}
export default props => <Field {...props} component={FileInput} />;
Hot to use it:
<FileInput
name="add_photo"
label="Others:"
classNameLabel="file-input-label"
className="file-input"
dropzone_options={{
multiple: false,
accept: 'image/*'
}}
>
<span>Add more</span>
</FileInput>
Another way to do it that will render a preview image (the below example uses React 16+ syntax and only accepts a single image file to send to an API; however, with some minor tweaks, it can also scale to multiple images and other fields inputs):
Working example: https://codesandbox.io/s/m58q8l054x
Working example (outdated): https://codesandbox.io/s/8kywn8q9xl
Before:
After:
containers/UploadForm.js
import React, { Component } from "react";
import { Form, Field, reduxForm } from "redux-form";
import DropZoneField from "../components/dropzoneField";
const imageIsRequired = value => (!value ? "Required" : undefined);
class UploadImageForm extends Component {
state = { imageFile: [] };
handleFormSubmit = formProps => {
const fd = new FormData();
fd.append("imageFile", formProps.imageToUpload.file);
// append any additional Redux form fields
// create an AJAX request here with the created formData
alert(JSON.stringify(formProps, null, 4));
};
handleOnDrop = (newImageFile, onChange) => {
const imageFile = {
file: newImageFile[0],
name: newImageFile[0].name,
preview: URL.createObjectURL(newImageFile[0]),
size: newImageFile[0].size
};
this.setState({ imageFile: [imageFile] }, () => onChange(imageFile));
};
resetForm = () => this.setState({ imageFile: [] }, () => this.props.reset());
render = () => (
<div className="app-container">
<h1 className="title">Upload An Image</h1>
<hr />
<Form onSubmit={this.props.handleSubmit(this.handleFormSubmit)}>
<Field
name="imageToUpload"
component={DropZoneField}
type="file"
imagefile={this.state.imageFile}
handleOnDrop={this.handleOnDrop}
validate={[imageIsRequired]}
/>
<button
type="submit"
className="uk-button uk-button-primary uk-button-large"
disabled={this.props.submitting}
>
Submit
</button>
<button
type="button"
className="uk-button uk-button-default uk-button-large"
disabled={this.props.pristine || this.props.submitting}
onClick={this.resetForm}
style={{ float: "right" }}
>
Clear
</button>
</Form>
<div className="clear" />
</div>
);
}
export default reduxForm({ form: "UploadImageForm" })(UploadImageForm);
components/dropzoneField.js
import React from "react";
import PropTypes from "prop-types";
import DropZone from "react-dropzone";
import ImagePreview from "./imagePreview";
import Placeholder from "./placeholder";
import ShowError from "./showError";
const DropZoneField = ({
handleOnDrop,
input: { onChange },
imagefile,
meta: { error, touched }
}) => (
<div className="preview-container">
<DropZone
accept="image/jpeg, image/png, image/gif, image/bmp"
className="upload-container"
onDrop={file => handleOnDrop(file, onChange)}
>
{({ getRootProps, getInputProps }) =>
imagefile && imagefile.length > 0 ? (
<ImagePreview imagefile={imagefile} />
) : (
<Placeholder
error={error}
touched={touched}
getInputProps={getInputProps}
getRootProps={getRootProps}
/>
)
}
</DropZone>
<ShowError error={error} touched={touched} />
</div>
);
DropZoneField.propTypes = {
error: PropTypes.string,
handleOnDrop: PropTypes.func.isRequired,
imagefile: PropTypes.arrayOf(
PropTypes.shape({
file: PropTypes.file,
name: PropTypes.string,
preview: PropTypes.string,
size: PropTypes.number
})
),
label: PropTypes.string,
onChange: PropTypes.func,
touched: PropTypes.bool
};
export default DropZoneField;
components/imagePreview.js
import React from "react";
import PropTypes from "prop-types";
const ImagePreview = ({ imagefile }) =>
imagefile.map(({ name, preview, size }) => (
<div key={name} className="render-preview">
<div className="image-container">
<img src={preview} alt={name} />
</div>
<div className="details">
{name} - {(size / 1024000).toFixed(2)}MB
</div>
</div>
));
ImagePreview.propTypes = {
imagefile: PropTypes.arrayOf(
PropTypes.shape({
file: PropTypes.file,
name: PropTypes.string,
preview: PropTypes.string,
size: PropTypes.number
})
)
};
export default ImagePreview;
components/placeholder.js
import React from "react";
import PropTypes from "prop-types";
import { MdCloudUpload } from "react-icons/md";
const Placeholder = ({ getInputProps, getRootProps, error, touched }) => (
<div
{...getRootProps()}
className={`placeholder-preview ${error && touched ? "has-error" : ""}`}
>
<input {...getInputProps()} />
<MdCloudUpload style={{ fontSize: 100, paddingTop: 85 }} />
<p>Click or drag image file to this area to upload.</p>
</div>
);
Placeholder.propTypes = {
error: PropTypes.string,
getInputProps: PropTypes.func.isRequired,
getRootProps: PropTypes.func.isRequired,
touched: PropTypes.bool
};
export default Placeholder;
components/showError.js
import React from "react";
import PropTypes from "prop-types";
import { MdInfoOutline } from "react-icons/md";
const ShowError = ({ error, touched }) =>
touched && error ? (
<div className="error">
<MdInfoOutline
style={{ position: "relative", top: -2, marginRight: 2 }}
/>
{error}
</div>
) : null;
ShowError.propTypes = {
error: PropTypes.string,
touched: PropTypes.bool
};
export default ShowError;
styles.css
img {
max-height: 240px;
margin: 0 auto;
}
.app-container {
width: 500px;
margin: 30px auto;
}
.clear {
clear: both;
}
.details,
.title {
text-align: center;
}
.error {
margin-top: 4px;
color: red;
}
.has-error {
border: 1px dotted red;
}
.image-container {
align-items: center;
display: flex;
width: 85%;
height: 80%;
float: left;
margin: 15px 10px 10px 37px;
text-align: center;
}
.preview-container {
height: 335px;
width: 100%;
margin-bottom: 40px;
}
.placeholder-preview,
.render-preview {
text-align: center;
background-color: #efebeb;
height: 100%;
width: 100%;
border-radius: 5px;
}
.upload-container {
cursor: pointer;
height: 300px;
}
I managed to do it with redux-form on material-ui wrapping TextField like this:
B4 edit:
After edit:
<Field name="image" component={FileTextField} floatingLabelText={messages.chooseImage} fullWidth={true} />
with component defined as:
const styles = {
button: {
margin: 12
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0
},
FFS:{
position: 'absolute',
lineHeight: '1.5',
top: '38',
transition: 'none',
zIndex: '1',
transform: 'none',
transformOrigin: 'none',
pointerEvents: 'none',
userSelect: 'none',
fontSize: '16',
color: 'rgba(0, 0, 0, 0.8)',
}
};
export const FileTextField = ({
floatingLabelText,
fullWidth,
input,
label,
meta: { touched, error },
...custom })=>{
if (input.value && input.value[0] && input.value[0].name) {
floatingLabelText = input.value[0].name;
}
delete input.value;
return (
<TextField
hintText={label}
fullWidth={fullWidth}
floatingLabelShrinkStyle={styles.FFS}
floatingLabelText={floatingLabelText}
inputStyle={styles.exampleImageInput}
type="file"
errorText={error}
{...input}
{...custom}
/>
)
}
If you need base64 encoding to send it to your backend, here is a modified version that worked for me:
export class FileInput extends React.Component {
getBase64 = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
onFileChange = async (e) => {
const { input } = this.props
const targetFile = e.target.files[0]
if (targetFile) {
const val = await this.getBase64(targetFile)
input.onChange(val)
} else {
input.onChange(null)
}
}
render() {
return (
<input
type="file"
onChange={this.onFileChange}
/>
)
}
}
Then your field component would look like:
<Field component={FileInput} name="primary_image" type="file" />
For React >= 16 and ReduxForm >= 8 (tested version are 16.8.6 for React and 8.2.5)
works following component.
(Solution posted in related GitHub issue by DarkBitz)
const adaptFileEventToValue = delegate => e => delegate(e.target.files[0]);
const FileInput = ({
input: { value: omitValue, onChange, onBlur, ...inputProps },
meta: omitMeta,
...props
}) => {
return (
<input
onChange={adaptFileEventToValue(onChange)}
onBlur={adaptFileEventToValue(onBlur)}
type="file"
{...props.input}
{...props}
/>
);
};
export const FileUpload = (props) => {
const { handleSubmit } = props;
const onFormSubmit = (data) => {
console.log(data);
}
return (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div>
<label>Attachment</label>
<Field name="attachment" component={FileInput} type="file"/>
</div>
<button type="submit">Submit</button>
</form>
)
}
With Redux Form
const { handleSubmit } = props;
//make a const file to hold the file prop.
const file = useRef();
// create a function to replace the redux-form input-file value to custom value.
const fileUpload = () => {
// jsx to take file input
// on change store the files /file[0] to file variable
return (
<div className='file-upload'>
<input
type='file'
id='file-input'
accept='.png'
onChange={(ev) => {
file.current = ev.target.files;
}}
required
/>
</div>
);
};
//catch the redux-form values!
//loop through the files and add into formdata
//form data takes key and value
//enter the key name as multer-config fieldname
//then add remaining data into the formdata
//make a request and send data.
const onSubmitFormValues = (formValues) => {
const data = new FormData();
for (let i = 0; i < file.current.length; i++) {
data.append("categoryImage", file.current[i]);
}
data.append("categoryName", formValues.categoryName);
Axios.post("http://localhost:8080/api/v1/dev/addNewCategory", data)
.then((response) => console.log(response))
.catch((err) => console.log(err));
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
You can also use react-dropzone for this purpose. The below code worked fine for me
filecomponent.js
import React from 'react'
import { useDropzone } from 'react-dropzone'
function MyDropzone(props) {
const onDrop = (filesToUpload) => {
return props.input.onChange(filesToUpload[0]);
}
const onChange = (filesToUpload) => {
return props.input.onChange(filesToUpload[0]);
}
const { getRootProps, getInputProps } = useDropzone({ onDrop });
return (
<div {...getRootProps()}>
<input {...getInputProps()} onChange={e => onChange(e.target.files)} />
<p> Drop or select yout file</p>
</div>
)
}
export default MyDropzone;
In form use this
<Field
name="myfile"
component={renderFile}
/>