React antd carousel methods - javascript

I am looking at using the antd Carousel, but I've not seen an example that describes how to use goTo(slideNumber, dontAnimate) method.
I have tried to use answers on this question react.js antd carousel with arrows to make goTo method works for me, but it didn't help, I always get carousel ref as null
import * as React from 'react';
import { createPortal } from 'react-dom';
import { Modal, Carousel } from 'antd'
export default class ImagePreviewCarousel extends React.Component<any, any> {
carousel = React.createRef();
componentDidMount() {
console.log(this.carousel);
}
render() {
const { url, imgList } = this.props;
const orderLayout = document.getElementById('order-layout');
const applicationLayout = document.getElementById('application');
return (
createPortal(<ImageViewer url={url} onClose={this.props.onClose} imgList={imgList} />, orderLayout || applicationLayout)
)
}
}
const ImageViewer = (props: IProps) => {
return (
<Modal
footer={null}
visible={props.onClose}
onCancel={props.onClose}
bodyStyle={{ backgroundColor: '#000' }}
width={'800px'}
>
<div style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginTop: 'auto',
marginBottom: 'auto',
width: '100%',
height: '100%',
zIndex: 10
}}>
<Carousel ref={node => (this.carousel = node)}>
{props.imgList}
</Carousel>
</div>
</Modal>
);
}
result of console.log(this.carousel) always returns null, what am i doing wrong?
p.s react version 16.4.1,

antd Carousel is an implementation of react-slick, you can check its API example.
Here is my example using hooks:
import React, { useRef, useState } from 'react';
import { Carousel, Row, InputNumber } from 'antd';
function App() {
const [slide, setSlide] = useState(0);
const slider = useRef();
return (
<div>
<Row style={{ marginBottom: 10 }}>
<InputNumber
min={0}
max={3}
value={slide}
onChange={e => {
setSlide(e);
slider.current.goTo(e);
}}
/>
</Row>
<Row>
<Carousel
dots={false}
ref={ref => {
console.log(ref);
slider.current = ref;
}}
>
<div>
<h3>0</h3>
</div>
<div>
<h3>1</h3>
</div>
</Carousel>
</Row>
</div>
);
}

You need to pass ref to your child component like,
<ImageViewer url={url} onClose={this.props.onClose} imgList={imgList} onRef={this.carousel} />
And can access in child component like,
<Carousel ref={props.onRef}>
{props.imgList}
</Carousel>
While printing in componentDidMount,
componentDidMount() {
console.log(this.carousel); // If this gives you ref object
console.log(this.carousel.current); //This will give you element
console.log(this.carousel.current.value); //This will give you element's value if element has value.
}
Simplified Demo using input.

Related

pass a data from a react component to another component which are on different routes

I have a CountryList react component
import React from "react";
import { Link } from "react-router-dom";
import { BsSearch } from "react-icons/bs";
export default function CountryList({
countries,
}: {
countries: any;
}): JSX.Element {
const [filter, setFilter] = React.useState("");
const [sortType, setSortType] = React.useState("");
console.log(filter);
const sorted = countries.sort((a: { name: string }, b: { name: any }) => {
const isReversed = sortType === "asc" ? 1 : -1;
return isReversed * a.name.localeCompare(b.name);
});
const onSort = (sortType: React.SetStateAction<string>) => {
console.log("changed");
setSortType(sortType);
};
return (
<div style={{ marginTop: "3rem" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
marginBottom: "10px",
}}
>
<div>List of countries</div>
<div style={{ display: "flex", alignItems: "center" }}>
<div style={{ position: "relative", marginRight: "1rem" }}>
<input
type="text"
placeholder="Filter"
name="namePrefix"
style={{ padding: "0.35rem" }}
onChange={(e: any) => {
setFilter(e.target.value);
}}
/>
<div style={{ position: "absolute", top: "5px", right: "5px" }}>
<BsSearch size="16" />
</div>
</div>
<div style={{ width: "8rem" }}>
<div className="btn-group">
<button
type="button"
className="btn dropdown-toggle sort-button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
{sortType === "asc"
? "Ascending"
: sortType === "desc"
? "Descending"
: "Select"}
</button>
<ul className="dropdown-menu sort-button">
<li>
<button
className="dropdown-item"
type="button"
onClick={() => onSort("asc")}
>
Ascending
</button>
</li>
<li>
<button
className="dropdown-item"
type="button"
onClick={() => onSort("desc")}
>
Descending
</button>
</li>
</ul>
</div>
</div>
</div>
</div>
<div className="country-list-items">
{countries &&
sorted.map((item: any, index: number) => (
<div key={index}>
<Link style={{ display: "block" }} to={`/regions`}>
{item.name}
</Link>
</div>
))}
</div>
<div
style={{ marginTop: "20px", display: "flex", justifyContent: "center" }}
>
{countries && countries.length > 10 ? (
<button className="secondary-button">Load More</button>
) : (
<p>There are no more countries</p>
)}
</div>
</div>
);
}
Now from this component I need to pass the data of selected country id while the user clicks on the Link of the respective country, which I will be able to get by {item.code}. Also on clicking the Link the user will be redirected to /regions route where the list of regions of the selected country from this component will be shown. This is the RegionList Component:
import React from "react";
import { Link } from "react-router-dom";
import { BsSearch } from "react-icons/bs";
export default function RegionList(): JSX.Element {
return (
<div style={{ marginTop: "3rem" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
marginBottom: "10px",
}}
>
<div>List of regions</div>
<div style={{ display: "flex", alignItems: "center" }}>
<div style={{ position: "relative", marginRight: "1rem" }}>
<input
type="text"
placeholder="Filter"
style={{ padding: "0.35rem" }}
/>
<div style={{ position: "absolute", top: "5px", right: "5px" }}>
<BsSearch size="16" />
</div>
</div>
<div style={{ width: "8rem" }}>
<select name="sort" id="sort">
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
</div>
</div>
</div>
<div className="country-list-items">
<div>
<Link style={{ display: "block" }} to={`/cities`}>
Alaska
</Link>
</div>
</div>
<div
style={{ marginTop: "20px", display: "flex", justifyContent: "center" }}
>
<button className="secondary-button">Load More</button>
<p>There are no more countries</p>
</div>
</div>
);
}
I need to pass the country id from the CountryList component to this RegionList component because I will do a GET network call in the RegionList component using the selected country id passed from the CountryList component. But I am not able to pass the country id data from CountryList component to RegionList component as they are on different routes and they do not have any common parent component. This is the route file for Countries
import { Route, Routes } from "react-router-dom";
import React from "react";
import CountryComponent from "../components/CountryComponent";
export class CountryRoute extends React.Component {
render() {
return (
<Routes>
<Route path="/" element={<CountryComponent />} />
</Routes>
);
}
}
here <CountryComponent /> is the mother component of CountryList
This is the route file for Regions:
import { Route, Routes } from "react-router-dom";
import React from "react";
import RegionComponent from "../components/RegionComponent";
export class RegionsRoute extends React.Component {
render() {
return (
<Routes>
<Route path="/" element={<RegionComponent />} />
</Routes>
);
}
}
here <RegionComponent /> is the mother component of RegionList
Here is the Main Component where all the components are called
import React from "react";
import { Routes, Route } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import styled from "styled-components";
import "styled-components/macro";
import { CountryRoute } from "../country/route";
import { RegionsRoute } from "../region/route";
import { CitiesRoute } from "../cities/route";
const MainContainer = styled.div`
min-height: 100%;
margin: 5rem;
`;
export const Main = (): JSX.Element => {
return (
<>
<>
<MainContainer>
<div style={{ textAlign: "center" }}>
<b>GEO SOFTWARE</b>
</div>
<div>
<div>
<Routes>
<Route path={"/countries*"} element={<CountryRoute />} />
<Route path={"/regions*"} element={<RegionsRoute />} />
<Route path={"/cities*"} element={<CitiesRoute />} />
</Routes>
</div>
</div>
<ToastContainer
toastClassName={"toastContainer e-12"}
hideProgressBar
position="bottom-left"
closeButton={false}
autoClose={5000}
bodyClassName={"toastBody"}
/>
</MainContainer>
</>
</>
);
};
Now how can I pass the selected country code data from CountryList to the RegionList component.
You can use Query Params for this. In the CountryList you can use the Link like this:
<Link style={{ display: "block" }} to={`/regions?country=COUNTRY_ID`}>
Then in the RegionsList youn can get that Query Parameter from the url and use as you want.
Check this example https://reactrouter.com/web/example/query-parameters
You could set up a simple "store" to keep track of the selected country independently of your component hierarchy.
The simplest possible store
A stripped down, simplest implementation possible might look something like this:
const data = {}
export default {
setCountry: c => data.country = c,
getCountry: () => data.country
}
Because the "store" data is a singleton, any component that imports the store will get the same info, regardless of where it is in the component tree.
import store from './store';
export default () => (
<div>{store.getCountry()}</div>
)
Listening for changes, etc.
The example above omits some details that may be important, depending on what you're doing, like updating views that have already rendered when the country value changes.
If you need that sort of thing you could make the store an event emitter so your components can listen for updates:
import Emitter from 'events';
class CountryStore extends Emitter {
data = {}
getCountry () {
return this.data.country;
}
setCountry (c) {
this.data.country = c;
this.emit('change'); // notify interested parties of the change
}
}
export default new CountryStore();
With the emitter in place, components can register for change notifications when they mount:
import store from './store';
function SomeComponent () {
useEffect(() => {
store.on('change', () => {
// do stuff when store changes happen
}, [])
})
return (<div>...</div>)
}
Custom Hook
To make it easy to do this wherever its needed you could wrap it all up in a custom hook that handles it all and returns the current value and a setter [country, setCountry] just like useState would:
const useCountry = () => {
const [country, setCountry] = useState(store.getCountry());
const handler = () => setCountry(store.getCountry());
useEffect(() => {
store.on('change', handler);
return () => store.off('change', handler);
})
return [country, c => store.setCountry(c)];
}
Then your components have it easy:
import useCountry from './useCountry.js';
export default function SomeComponent () {
const [country, setCountry] = useCountry();
return (
<div>
<div>Current Country: {country}</div>
<button onClick={() => setCountry(Math.random())}>Change Country</button>
</div>
)
}
There are off-the-shelf libraries that will do all of this and more for you, but I thought it might be more helpful to explain an actual rudimentary implementation.
You can have some sort of global state country_id which is initially equal to null.
When user clicks on a country, set that country_id to be equal to the clicked country id.
Now, Inside you RegionList component you can access the country id through country_id state.
You can achieve the state management by different ways:
Prop drilling
Context API
Use Redux or Recoil to handle state-management
As others have pointed out, this is 100% what context is for.
It looks like this:
import React, { createContext, useContext } from 'react';
const MyCountryContext = createContext(null);
export const useCountry = () => useContext(MyCountryContext);
export const MyCountryContext = ({children}) => {
const [country,setCountry] = useState();
return (
<MyCountryContext.Provider value={[country,setCountry]}>
{children}
</MyCountryContext.Provider>
)
}
Use it like this:
export const Main = (): JSX.Element => {
return (
<MyCountryContext>
...rest of your tree
</MyCountryContext>
);
}
Then, in any components that are below MyCountryContext you can use the hook just like useState:
import { useCountry } from './MyCountryContext';
const MyComponentThatUsesCountry = () => {
const [country,setCountry] = useCountry();
return (...)
}

React export component that is not diplayed to PNG

I'm trying to export a chart to an image and I want the chart image to have a custom legend that is not being displayed on screen.
How can I do that?
For now I have tried to export using react-component-export-image but if the component is not displayed the ref is null and It cannot be exported. See component export implementation src-code.
Example of my current code: codesandbox
The only way you can achieve that by manipulating the canvas before render. You can do that by setting the onclone option in html2CanvasOptions.
import { Line } from "react-chartjs-2";
import { exportComponentAsPNG } from "react-component-export-image";
import React, { useRef } from "react";
import { data } from "./data";
const Chart = React.forwardRef((props, ref) => {
return (
<div ref={ref} style={{ maxWidth: "800px" }}>
<Line data={data} height={80} />
<div id="legend" style={{ textAlign: "center", visibility: "hidden" }}>
Legend
</div> {/* Visibility set to hidden using css */}
</div>
);
});
const App = () => {
const componentRef = useRef();
return (
<React.Fragment>
<Chart ref={componentRef} />
<button
style={{ margin: "30px" }}
onClick={() => exportComponentAsPNG(componentRef, {
html2CanvasOptions: {
onclone: (clonedDoc) => {
clonedDoc.getElementById("legend").style.visibility = "visible";
// Visibility set to visible using `onclone` method
},
},
})
}
>
Export As PNG
</button>
</React.Fragment>
);
};
export default App;
https://codesandbox.io/s/export-chart-821kc?file=/src/App.js
This will do the job. Let me know if you need further support.

Passing function as props in Reactjs

I am trying to pass function as prop. I did this before but now with the same logic it is giving me error (this.props.functionName is not a function).
I have a child (Navbar) and a parent component(MainComponent). I want to send a input value from Navbar to MainComponet and set it to the state value in parent Component.
Parent Component
import React ,{Component}from 'react'
import Navbar from '../Presentational/Navbar'
class Main extends Component{
constructor(props){
super(props)
this.state = {
searchItem: ''
}
}
GetSearchItem(search){
this.setState({searchItem:search})
}
render(){
return(
<div className = 'container'>
<div className = 'row'>
<div className = 'col-12 mt-1'>
<Navbar onChange = {(search)=>this.GetSearchItem(search)}></Navbar>
</div>
</div>
<div className = 'row'>
<div className = 'col-3'>
<h3>{this.state.searchItem}</h3>
</div>
</div>
</div>
)
}
}
export default Main
Child Component (Navbar)
import React,{Component} from 'react'
import {AppBar,Toolbar,IconButton,Typography,InputBase} from '#material-ui/core'
import MenuIcon from '#material-ui/icons/Menu';
import SearchIcon from '#material-ui/icons/Search';
import {fade , makeStyles} from '#material-ui/core/styles'
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.15),
'&:hover': {
backgroundColor: fade(theme.palette.common.white, 0.25),
},
marginLeft: 0,
width: '100%',
[theme.breakpoints.up('sm')]: {
marginLeft: theme.spacing(1),
width: 'auto',
},
},
searchIcon: {
padding: theme.spacing(0, 2),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
inputRoot: {
color: 'inherit',
},
inputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: '12ch',
'&:focus': {
width: '20ch',
},
},
},
}));
class Navbar extends Component{
render(){
const classes = this.props.classes;;
return(
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="open drawer"
>
<MenuIcon />
</IconButton>
<Typography className={classes.title} variant="h6" noWrap>
Pizaa Valley
</Typography>
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<InputBase
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
inputProps={{ 'aria-label': 'search' }}
onChange={(event)=>this.props.onChange(event.target.value)}
/>
</div>
</Toolbar>
</AppBar>
</div>
)
}
}
export default () => {
const classes = useStyles();
return (
<Navbar classes={classes} />
)
}
The problem is that you have two Navbar types. You first have the class component created using class Navbar. And second you have the following functional component defined here:
export default () => {
const classes = useStyles();
return (
<Navbar classes={classes} />
)
}
When you do
import Navbar from '../Presentational/Navbar'
<Navbar onChange = {(search)=>this.GetSearchItem(search)}></Navbar>
The onChange prop is correctly given to the functional component, but is never passed along to the class-based component. You can fix this by replacing your functional component with the below code:
export default props => {
const classes = useStyles();
return (
// using the "spread operator", we pass along all the props given
// to the functional component, so the class-based component can
// also access these
<Navbar {...props} classes={classes} />
)
}
you've done everything correctly except change this:
GetSearchItem(search){
this.setState({searchItem:search})
}
to
GetSearchItem = (search) => {
this.setState({searchItem:search})
}
as an arrow function it has access to the scope above
Try with the following:-
In your parent component modified the below line:-
<Navbar onChangeCallBack = {(search)=>this.GetSearchItem(search)}></Navbar>
In your child Navbar component only modified the below line:-
onChange={(event)=>this.props.onChangeCallBack(event.target.value)}

Use fat arrow function to change React.Component in React-Native

is it possible to render a React.Component over other React.Component using just fat arrow function, using state seems unnecessary in my case as there is no need to close the opened Component. I am trying to achieve the simplest to render a React.Component over other React.Component.
I am trying to do it like this:
<Button onPress={() => { return (<ShowOtherReactComponent/>); }} >Show OtherComponent</Button>
this is calling the <ShowOtherReactComponent/> I know that because I called an alert function from constructor but! nothing is rendering. why is that? how can I do this?
PS: this approach may be wrong, but still wanna see how it can be done. for science.
You shouldn't return jsx from your handlers. Usually to show and or toggle components conditional rendering is the way to go.
Instead of returning <ShowOtherReactComponent/> from onPress you conditionally render the component based on a boolean binded to the local state and change the state instead.
const Component = () =>{
const [show, setShow] = useState(false)
const onPress = () => setShow(true)
return(
<>
<button onPress={onPress}> Show </button>
{ show && <ShowOtherReactComponent/> }
</>
)
}
I've made an example to show what you could potentially do if you wanted a button to add components to display:
import React from 'react';
import autoBind from 'react-autobind';
export default class ButtonTest extends React.Component {
constructor(props) {
super(props);
this.state = {
extraComponents : []
};
autoBind(this);
}
addComponent() {
const newComponent = (<p>I'm a new component</p>);
this.setState({extraComponents: [...this.state.extraComponents, newComponent]})
}
render() {
return (
<div>
<button onClick={this.addComponent}>add component</button>
{this.state.extraComponent}
</div>
)
}
}
I've checked it and it works.
import React, { useState } from 'react'
import { SafeAreaView, View, Text, Button, Dimensions } from 'react-native'
const App = () => {
const [visibilityOfOtherView, setvisibilityOfOtherView] = useState(false)
const { height, width } = Dimensions.get('window')
const SCREEN_HEIGHT = Math.round(height)
const SCREEN_WIDTH = Math.round(width)
return (
<SafeAreaView style={{ height: SCREEN_HEIGHT, width: SCREEN_WIDTH, }}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'red' }}>
<Text style={{ marginBottom: 20 }}>
First Components
</Text>
<Button
title='Toggle Components View'
onPress={() => setvisibilityOfOtherView(!visibilityOfOtherView)}
/>
</View>
{
visibilityOfOtherView ?
<View style={{ height: SCREEN_HEIGHT, width: SCREEN_WIDTH, alignItems: 'center', justifyContent: 'center', backgroundColor: 'green' }}>
<Text style={{ marginBottom: 20 }}>
Secound Components
</Text>
<Button
title='Toggle Components View'
onPress={() => setvisibilityOfOtherView(!visibilityOfOtherView)}
/>
</View>
: null
}
</SafeAreaView>
)
}
export default App

How to passing data value from map to Material UI ButtonBase onClick event

I have an array data that rendered with map and wrapped with Material Ui ButtonBase component. I want to get the data name if button is clicked.
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Card, { CardContent } from 'material-ui/Card';
import Typography from 'material-ui/Typography';
import ButtonBase from "material-ui/ButtonBase";
const styles = theme => ({
card: {
textAlign: 'center',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
cardButton: {
display: "block",
textAlign: "initial",
}
});
class SimpleMediaCard extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
name: 'Javascript',
image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGLecy3onT9rChTsw1BawUkuOxKE1r6yx_ViYXjqpBq8zsE_BI'
},
{
name: 'React',
image: 'https://lapraim.com/assets/partners/react-logo.png'
}
]
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(evt) {
alert('Name : ');
}
render() {
const { classes } = this.props;
const { data } = this.state;
const { handleClick } = this;
return (
<div>
{data.map(function(item, i) {
return (
<div key={i}>
<ButtonBase className={classes.cardButton} onClick={handleClick}>
<Card className={classes.card}>
<img src={item.image} height='100px' alt={item.name}/>
<CardContent>
<Typography component="h2">
{item.name}
</Typography>
</CardContent>
</Card>
</ButtonBase>
</div>
)
})}
</div>
)
}
}
SimpleMediaCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleMediaCard);
This is the demo code link
At code above if picture is clicked it will show an alert.
I want to show the data name on each clicked picture.
Can anyone help me to show data name every picture is clicked?
You mean something like this?
handleClick(item) {
alert('Name : ' + item.name);
}
<ButtonBase className={classes.cardButton} onClick={() => handleClick(item)}>
Just pass the item to the event handler.

Categories