react-ultimate-pagination component setup - javascript

I'm trying to use this package react-ultimate-pagination: https://github.com/ultimate-pagination/react-ultimate-pagination
I want to set it up like their basic demo example: https://codepen.io/dmytroyarmak/pen/GZwKZJ
The usage instructions at the bottom of the github page say to import the component like this:
import ReactUltimatePagination from 'react-ultimate-pagination';
But the codepen demo just shows a constant:
const UltimatePagination = reactUltimatePaginationBasic.default;
I copied the code from the demo, but since it is mismatched with the import, I have an error of UltimatePagination being undefined and reactUltimatePaginationBasic undefined.
Does anyone know how to set up this component like the demo example?

The module exports the higher oder component createUltimatePagination as a named export. To import it using es6 import syntax it has to be the following:
import {createUltimatePagination} from 'react-ultimate-pagination';
Example App:
import React, { Component } from "react";
import { render } from "react-dom";
import { createUltimatePagination } from "react-ultimate-pagination";
const Button = ({ value, isActive, disabled, onClick }) => (
<button
style={isActive ? { fontWeight: "bold" } : null}
onClick={onClick}
disabled={disabled}
>
{value}
</button>
);
const PaginatedPage = createUltimatePagination({
itemTypeToComponent: {
PAGE: Button,
ELLIPSIS: () => <Button value="..." />,
FIRST_PAGE_LINK: () => <Button value="First" />,
PREVIOUS_PAGE_LINK: () => <Button value="Prev" />,
NEXT_PAGE_LINK: () => <Button value="Next" />,
LAST_PAGE_LINK: () => <Button value="Last" />
}
});
class App extends Component {
state = {
page: 1
};
render() {
return (
<PaginatedPage
totalPages={10}
currentPage={this.state.page}
onChange={page => this.setState({ page })}
/>
);
}
}
render(<App />, document.getElementById("root"));
Also see this working example on codesandbox.
To be honest I played around with the api of that library and actually it is unclear to me how this library is intended to be used. A pagination component should receive a list of items and then provide a render prop to render the current page with a slice of these items. It's a pagination that does not paginate. Basically it's only a button bar.

Just use var ReactUltimatePagination = require('react-ultimate-pagination'); after you've installed it with npm install react-ultimate-pagination --save

Related

Reload a page after the initial load with Next.js

I have a route called "./checkout" that renders embedded elements from Xola. The issue is I am using client side routing and the page needs a refresh to load the checkout page correctly (if not, Xola elements do not show up on the DOM 1). When I try to reload the page on the initial load I get an infinite reload loop. I can't use a href for specific reasons so I need to continue to use Next.js routing. Anyway I can go about this? EDIT: I have reached out to Xola support team for further assistance.
After refresh
checkout.js
import Head from "next/head";
import { useRouter } from "next/router";
import { Container, Button } from "#mui/material";
import { makeStyles } from "#mui/styles";
import { CheckoutCard } from "../components/layout/directory";
import useIsSsr from "#/config/useSsr";
function Checkout() {
const isSsr = useIsSsr();
const router = useRouter();
const classes = useStyles();
return (
<>
{isSsr ? null : window.location.reload()}
<Head>
<title>checkout</title>
</Head>
<Container className={classes.root}>
<Button
className={classes.btn}
onClick={router.back}
color="secondary"
variant={"contained"}
>
back
</Button>
<CheckoutCard />
</Container>
</>
);
}
const useStyles = makeStyles((theme) => ({
root: { marginTop: theme.spacing(10) },
btn: { marginBottom: theme.spacing(5) },
}));
export default Checkout;
CheckoutCard.js
function CheckoutCard() {
return (
<div
className="xola-embedded-checkout"
data-seller="5f3d889683cfdc77b119e592"
data-experience="5f3d8d80d6ba9c6b14748160"
data-version="2"
id="xola-checkout"
></div>
);
}
export default CheckoutCard;
Please add one more prop to CheckoutCard component calling in checkout.js.
You need to update
<CheckoutCard
url={`https://checkout.xola.com/index.html#seller/5f3d889683cfdc77b119e592/experiences/${
url && url.slice(1)
}?openExternal=true`}
/>
to
<CheckoutCard
url={`https://checkout.xola.com/index.html#seller/5f3d889683cfdc77b119e592/experiences/${
url && url.slice(1)
}?openExternal=true`}
key={new Date().getTime()}
/>
"key" prop is to identify the component and you are going to use external service ( like iframe, not sure correctly )
So in order to render the embedded elements from Xola, you should add "key" prop for CheckoutCard component calling.

MaterialUI Redux connect() using TextArea and submitting form. Warning about refs in func components [duplicate]

I have the following (using Material UI)....
import React from "react";
import { NavLink } from "react-router-dom";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
function LinkTab(link){
return <Tab component={NavLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
In the new versions this causes the following warning...
Warning: Function components cannot be given refs. Attempts to access
this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of ForwardRef.
in NavLink (created by ForwardRef)
I tried changing to...
function LinkTab(link){
// See https://material-ui.com/guides/composition/#caveat-with-refs
const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
return <Tab component={MyLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
But I still get the warning. How do I resolve this issue?
Just give it as innerRef,
// Client.js
<Input innerRef={inputRef} />
Use it as ref.
// Input.js
const Input = ({ innerRef }) => {
return (
<div>
<input ref={innerRef} />
</div>
)
}
NavLink from react-router is a function component that is a specialized version of Link which exposes a innerRef prop for that purpose.
// required for react-router-dom < 6.0.0
// see https://github.com/ReactTraining/react-router/issues/6056#issuecomment-435524678
const MyLink = React.forwardRef((props, ref) => <NavLink innerRef={ref} {...props} />);
You could've also searched our docs for react-router which leads you to https://mui.com/getting-started/faq/#how-do-i-use-react-router which links to https://mui.com/components/buttons/#third-party-routing-library. The last link provides a working example and also explains how this will likely change in react-router v6
You can use refs instead of ref. This only works as it avoids the special prop name ref.
<InputText
label="Phone Number"
name="phoneNumber"
refs={register({ required: true })}
error={errors.phoneNumber ? true : false}
icon={MailIcon}
/>
In our case, we were was passing an SVG component (Site's Logo) directly to NextJS's Link Component which was a bit customized and we were getting such error.
Header component where SVG was used and was "causing" the issue.
import Logo from '_public/logos/logo.svg'
import Link from '_components/link/Link'
const Header = () => (
<div className={s.headerLogo}>
<Link href={'/'}>
<Logo />
</Link>
</div>
)
Error Message on Console
Function components cannot be given refs. Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
Customized Link Component
import NextLink from 'next/link'
import { forwardRef } from 'react'
const Link = ({ href, shallow, replace, children, passHref, className }, ref) => {
return href ? (
<NextLink
href={href}
passHref={passHref}
scroll={false}
shallow={shallow}
replace={replace}
prefetch={false}
className={className}
>
{children}
</NextLink>
) : (
<div className={className}>{children}</div>
)
}
export default forwardRef(Link)
Now we made sure we were using forwardRef in the our customized Link Component but we still got that error.
In order to solve it, I changed the wrapper positioning of SVG element to this and :poof:
const Header = () => (
<Link href={'/'}>
<div className={s.headerLogo}>
<Logo />
</div>
</Link>
)
If you find that you cannot add a custom ref prop or forwardRef to a component, I have a trick to still get a ref object for your functional component.
Suppose you want to add ref to a custom functional component like:
const ref = useRef();
//throws error as Button is a functional component without ref prop
return <Button ref={ref}>Hi</Button>;
You can wrap it in a generic html element and set ref on that.
const ref = useRef();
// This ref works. To get button html element inside div, you can do
const buttonRef = ref.current && ref.current.children[0];
return (
<div ref={ref}>
<Button>Hi</Button>
</div>
);
Of course manage state accordingly and where you want to use the buttonRef object.
to fix this warning you should wrap your custom component with the forwardRef function as mentioned in this blog very nicely
const AppTextField =(props) {return(/*your component*/)}
change the above code to
const AppTextField = forwardRef((props,ref) {return(/*your component*/)}
const renderItem = ({ item, index }) => {
return (
<>
<Item
key={item.Id}
item={item}
index={index}
/>
</>
);
};
Use Fragment to solve React.forwardRef()? warning
If you're using functional components, then React.forwardRef is a really nice feature to know how to use for scenarios like this. If whoever ends up reading this is the more hands on type, I threw together a codesandbox for you to play around with. Sometimes it doesn't load the Styled-Components initially, so you may need to refresh the inline browser when the sandbox loads.
https://codesandbox.io/s/react-forwardref-example-15ql9t?file=/src/App.tsx
// MyAwesomeInput.tsx
import React from "react";
import { TextInput, TextInputProps } from "react-native";
import styled from "styled-components/native";
const Wrapper = styled.View`
width: 100%;
padding-bottom: 10px;
`;
const InputStyled = styled.TextInput`
width: 100%;
height: 50px;
border: 1px solid grey;
text-indent: 5px;
`;
// Created an interface to extend the TextInputProps, allowing access to all of its properties
// from the object that is created from Styled-Components.
//
// I also define the type that the forwarded ref will be.
interface AwesomeInputProps extends TextInputProps {
someProp?: boolean;
ref?: React.Ref<TextInput>;
}
// Created the functional component with the prop type created above.
//
// Notice the end of the line, where you wrap everything in the React.forwardRef().
// This makes it take one more parameter, called ref. I showed what it looks like
// if you are a fan of destructuring.
const MyAwesomeInput: React.FC<AwesomeInputProps> = React.forwardRef( // <-- This wraps the entire component, starting here.
({ someProp, ...props }, ref) => {
return (
<Wrapper>
<InputStyled {...props} ref={ref} />
</Wrapper>
);
}); // <-- And ending down here.
export default MyAwesomeInput;
Then on the calling screen, you'll create your ref variable and pass it into the ref field on the component.
// App.tsx
import React from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";
import MyAwesomeInput from "./Components/MyAwesomeInput";
const App: React.FC = () => {
// Set some state fields for the inputs.
const [field1, setField1] = React.useState("");
const [field2, setField2] = React.useState("");
// Created the ref variable that we'll use down below.
const field2Ref = React.useRef<TextInput>(null);
return (
<View style={styles.app}>
<Text>React.forwardRef Example</Text>
<View>
<MyAwesomeInput
value={field1}
onChangeText={setField1}
placeholder="field 1"
// When you're done typing in this field, and you hit enter or click next on a phone,
// this makes it focus the Ref field.
onSubmitEditing={() => {
field2Ref.current.focus();
}}
/>
<MyAwesomeInput
// Pass the ref variable that's created above to the MyAwesomeInput field of choice.
// Everything should work if you have it setup right.
ref={field2Ref}
value={field2}
onChangeText={setField2}
placeholder="field 2"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
app: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default App;
It's that simple! No matter where you place the MyAwesomeInput component, you'll be able to use a ref.
I just paste here skychavda solution, as it provide a ref to a child : so you can call child method or child ref from parent directly, without any warn.
source: https://github.com/reactjs/reactjs.org/issues/2120
/* Child.jsx */
import React from 'react'
class Child extends React.Component {
componentDidMount() {
const { childRef } = this.props;
childRef(this);
}
componentWillUnmount() {
const { childRef } = this.props;
childRef(undefined);
}
alertMessage() {
window.alert('called from parent component');
}
render() {
return <h1>Hello World!</h1>
}
}
export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';
class Parent extends React.Component {
onClick = () => {
this.child.alertMessage(); // do stuff
}
render() {
return (
<div>
<Child childRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.alertMessage()</button>
</div>
);
}
}

Odd behavior with react-modal

I'm trying to build a quiz that uses react-modal to provides hints. I will need multiple modals inside the quiz. I'm new to React so it's quite possible that I'm making a simple mistake.
I'm not sure it matters, but I've built this using create-react-app.
My App.js looks like this:
import React, { Component } from 'react';
import HintModal from './hintModal';
import Modal from 'react-modal';
import './App.css';
Modal.setAppElement('#root');
class App extends Component {
state = {
modalIsOpen: false,
hint: ''
};
openModal = (hint) => {
this.setState({ modalIsOpen: true, hint: hint });
}
closeModal = () => {
this.setState({ modalIsOpen: false, hint: '' });
}
render() {
return (
<React.Fragment>
<h1>Modal Test</h1>
<h2>First Modal</h2>
<HintModal
modalIsOpen={this.state.modalIsOpen}
openModal={this.openModal}
closeModal={this.closeModal}
hint="mango"
/>
<hr />
<h2>Second Modal</h2>
<HintModal
modalIsOpen={this.state.modalIsOpen}
openModal={this.openModal}
closeModal={this.closeModal}
hint="banana"
/>
</React.Fragment>
);
}
}
export default App;
hintModal.jsx looks like this:
import React, { Component } from 'react';
import Modal from 'react-modal';
const HintModal = (props) => {
const {openModal, modalIsOpen, closeModal, hint} = props;
return (
<React.Fragment>
<button onClick={ () => openModal(hint) }>Open Modal</button>
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
contentLabel="Example Modal"
>
<h2>Hint</h2>
<p>{hint}</p>
<button onClick={closeModal}>Close</button>
</Modal>
<p>We should see: {hint}</p>
</React.Fragment>
);
};
export default HintModal;
Here's the problem: I need the content of the modal to change based on the hint prop passed to HintModal. When I output hint from outside <Modal>, it behaves as expected, displaying the value of the prop. But when I output hint within <Modal>, it returns "banana" (the value of the hint prop for the second instance of HintModal) when either modal is activated.
Any help would be greatly appreciated!
You are controlling all of your modals with the same piece of state and the same functions to open and close the modal.
You need to either have just one modal and then dynamically render the message inside it or you need to store a modalIsOpen variable in your state for every single modal.

Conditional render is not updating with setState()

I have a form that I would like to update depending on the state of a toggle in that form. Here is my container component with the form:
import React, { Component } from 'react';
import {
Create,
Edit,
NumberInput,
SimpleForm,
TextInput
} from 'admin-on-rest';
import LatLngInput from '../customInputs/LatLngInput';
import UTMInput from '../customInputs/UTMInput';
import UTMSwitch from '../customInputs/UTMSwitch';
export class LocationEdit extends Component {
constructor(props) {
super(props);
this.state = {
utmInput: false,
utm: {
easting: 0,
northing: 0,
isSouthern: false,
zone: 0
}
};
}
toggleUTM() {
this.setState(prevState => ({ utmInput: !prevState.utmInput }), () => {
console.log(this.state.utmInput);
});
}
render() {
return (
<Edit title={<LocationTitle />} {...this.props}>
<SimpleForm validate={validateLocationCreation}>
<TextInput source="name" />
{this.state.utmInput ? (
<UTMInput />
) : (
<LatLngInput />
)}
<UTMSwitch defaultToggled={this.state.utmInput} onToggle={this.toggleUTM.bind(this)}/>
</SimpleForm>
</Edit>
);
}
}
The toggle is supposed to switch between two input fields: UTMInput and LatLngInput. These are currently pretty similar with the exception of their labels:
UTMInput:
import React from 'react';
import { Field } from 'redux-form';
import { NumberInput } from 'admin-on-rest';
const UTMInput = () => (
<span>
<Field name="latitude" component={NumberInput} label="Northing" />
<br />
<Field name="longitude" component={NumberInput} label="Easting" />
</span>
);
export default UTMInput;
LatLngInput:
import React from 'react';
import { Field } from 'redux-form';
import { NumberInput } from 'admin-on-rest';
const LatLngInput = () => (
<span>
<Field name="latitude" component={NumberInput} label="Latitude" />
<br />
<Field name="longitude" component={NumberInput} label="Longitude" />
</span>
);
export default LatLngInput;
I understand that setState by itself does not guarantee a UI update, which is why I've included the console.log(this.state.utmInput) as a callback to the setState function in toggleUTM (this logs alternating true and false to the console as expected). I've also tried the other form of setState which accepts a function instead of an object, as the React docs suggest. I've even tried using this.forceUpdate() after the console.log(this.state.utmInput). None of these have worked.
I've used breakpoints in VSCode and I can confirm that the setState function is being called each time I toggle the switch but the conditional ({this.state.utmInput ?...) is not being called. I'm using the admin-on-rest framework, although I don't know if this is the issue. I've checked the source code and shouldComponentUpdate is not being used in any of the components I've imported from that framework (<Edit />, <SimpleForm />, <TextInput /> or <NumberInput />).
Any help would be very much appreciated!
I tried putting together an example repo that reproduces the error, but it worked fine in this new example. Turns out, despite my best guess, the Admin On Rest framework was the problem.
Upgrading to version 1.4.0 from 1.3.2 solved my issue.

JSreact child component error

I edited code that was working perfectly fine, until I added new code to make the button clicking work from video to video. I just can't find the error, and the terminal is not picking it up either.
Can someone tell me why the ./video_list_item.js is not being recognized anymore?
Attached is the parent, and 2 child components, though I have 5 total components the error is definitely only in one of the two.
index.js
import React, {Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/searchbar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
const API_KEY = 'AIzaSyAi1CzVpifuFUDVQf3dzrTu3mwJDP2n8r8';
class App extends Component {
constructor(props){
super(props);
//Do i expect this component to play any type of state? aka pass props
this.state= {
videos: [],
selectedVideo:null
};
// ^proper name can be anything
YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
// console.log(data);
this.setState({ videos:videos,
selectedVideo: videos[0]
});
}); // this.setState({videos : vidoos});
}
render (){
return (
<div>
<SearchBar />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
video_list.js
//video list file. JS.react
import React from 'react';
import VideoListItem from './video_list_item';
const VideoList = (props) => {
// ^props is made args here because videos var is passed
// in index.js into VideoList function(with state).
const videoItems = props.videos.map((video) => {
return (
<VideoListItem
onVideoSelect={props.onVideoSelect}
key={video.etag}
video ={video} />
);
});
return (
<ul className="col-md-4 list-group">
{videoItems}
</ul>
);
};
export default VideoList;
video_list.item.js
//video list item file. JS.react
import React from 'react';
const VideoListItem = ({video, onVideoSelect}) => {
const imageUrl = video.snippet.thumbnails.default.url;
// can see this in console log
return (
<li onClick={() => onVideoSelect{video} }className="list-group-item">
<div className ="video-list media">
<div className ="media-left">
<img className="media-object" src = {imageUrl}/>
</div>
<div className="media-body">
<div className="media-heading"> {video.snippet.title} </div>
</div>
</div>
</li>
);
};
export default VideoListItem;
I can post the error message I get in the dev tools, but it literally just says one thing. This is the error message => Cannot find module "./video_list_item"
Also, no files were moved around at all, the code was edited and that created the error message. Thanks for anyone who sincerely answers this question!
<li onClick={() => onVideoSelect{video} }className="list-group-item">
The error is the {video} should actually be in parenthesis like so (video).
correct code is:
<li onClick={() => onVideoSelect(video) }className="list-group-item">.
Note: The {} makes it so the child component is not recognized by the parent for some strange reason. Thanks to all those who helped in answering!

Categories