menuLinks.map is not a function - reactjs

I am trying to call a request with graphiQL but something is wrong with it. Is anybody can help me? I am getting this error:
TypeError: menuLinks.map is not a function
It is working on gatsby/react
import React from "react"
import { graphql, StaticQuery, Link } from "gatsby"
import { Menu } from "antd"
import headerStyles from "./headerStyles.module.scss"
class Header extends React.Component {
render() {
const menuLinks = props.data.site.siteMetadata
return (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
menuLinks {
name
link
}
}
}
}
`}
render={data => (
<div data={data} className={headerStyles.menu}>
<Link to="/">
<img
style={{ width: "30px", float: "left" }}
/>
</Link>
<Menu mode="horizontal" breakpoint="lg" collapsedWidth="0">
{menuLinks.map(link => (
<Menu.Item key={link.name}>
<Link to={link.link}>{link.name}</Link>
</Menu.Item>
))}
</Menu>
</div>
)}
/>
)
}
}
export default Header

const menuLinks = this.props.data.site.siteMetadata
instead of
const menuLinks = props.data.site.siteMetadata
How to access props in react you can check this props
In Class based Component
this.props.data
In function based component
props.data

You should use this.props.data.site.siteMetadata instead of props.data.site.siteMetadata because you are using Class component.
And things can go wrong in these cases. You have to check whether data, site, and siteMetadata existed either in the componentDidMount or render. Most likely, in the first render your props.data.site.siteMetadata might not exist.
Change your mapping to this code.
{
this.props.data
&& this.props.data.site
&& this.props.site.siteMetadata
&& this.props.site.siteMetadata.length > 0
? this.props.site.siteMetadata.map(each => <MenuItem />)
: <Loading />
}

Related

React app looking for material-ui/core in Src folder and not node_modules

I am trying to create a material ui drawer menu (but due to the amount of links I need it to be nested).
I've found exactly what I need here,
https://medium.com/gammastack/making-a-nested-sidebar-menu-in-react-f8595031995e
(Same as the menu in material-ui site)
I have followed it to the letter (Many times now) and I'm getting this error
./src/MenuBar.jsx
Module not found: Can't resolve 'material-ui/core/Collapse' in 'C:\Users\adejo\Desktop\MUI-problem\nested-menu\src'
It seems to me that it's looking in the Src folder for all of the mui components, and not node_modules (where I thought it would be). I'm pretty new to all of this, and usually get by with Google, but I'm stuck on this one. Can anyone suggest how to go about resolving this?
I haven't included code as it is exactly as is on the link.
I have only changed what is on the link, I put the menuItems.json file in Src, and everything else is as it comes.
Code for MenuBar
import React, { Component } from 'react'
import List from 'material-ui/core/List'
import ListItem from 'material-ui/core/ListItem'
import ListItemText from 'material-ui/core/ListItemText'
import Collapse from 'material-ui/core/Collapse'
import ExpandLess from 'material-ui/icons/ExpandLess'
import ExpandMore from 'material-ui/icons/ExpandMore'
import Drawer from 'material-ui/core/Drawer'
import { withStyles } from 'material-ui/core/styles'
import { Link } from 'react-router-dom'
import menuItems from './menuItems'
const styles = {
list: {
width: 250,
},
links: {
textDecoration:'none',
},
menuHeader: {
paddingLeft: '30px'
}
};
class MenuBar extends Component {
constructor( props ) {
super( props )
this.state = {}
}
// this method sets the current state of a menu item i.e whether it is in expanded or collapsed or a collapsed state
handleClick( item ) {
this.setState( prevState => (
{ [ item ]: !prevState[ item ] }
) )
}
// if the menu item doesn't have any child, this method simply returns a clickable menu item that redirects to any location and if there is no child this method uses recursion to go until the last level of children and then returns the item by the first condition.
handler( children ) {
const { classes } = this.props
const { state } = this
return children.map( ( subOption ) => {
if ( !subOption.children ) {
return (
<div key={ subOption.name }>
<ListItem
button
key={ subOption.name }>
<Link
to={ subOption.url }
className={ classes.links }>
<ListItemText
inset
primary={ subOption.name }
/>
</Link>
</ListItem>
</div>
)
}
return (
<div key={ subOption.name }>
<ListItem
button
onClick={ () => this.handleClick( subOption.name ) }>
<ListItemText
inset
primary={ subOption.name } />
{ state[ subOption.name ] ?
<ExpandLess /> :
<ExpandMore />
}
</ListItem>
<Collapse
in={ state[ subOption.name ] }
timeout="auto"
unmountOnExit
>
{ this.handler( subOption.children ) }
</Collapse>
</div>
)
} )
}
render() {
const { classes, drawerOpen, menuOptions } = this.props
return (
<div className={classes.list}>
<Drawer
variant="persistent"
anchor="left"
open
classes={ { paper: classes.list } }>
<div>
<List>
<ListItem
key="menuHeading"
divider
disableGutters
>
<ListItemText
className={ classes.menuHeader }
inset
primary="Nested Menu"
/>
</ListItem>
{ this.handler( menuItems.data ) }
</List>
</div>
</Drawer>
</div>
)
}
}
export default withStyles(styles)(MenuBar)
Thank You
Please check your node_modules folder for material-ui folder. check if its #material-ui or just material-ui.
your imports are wrong. it should be as follows with # sign.
e.g.
import Collapse from '#material-ui/core/Collapse';
if you have freshly install material-ui then it may be #mui folder with imports as follows
import Collapse from '#mui/material/Collapse';

Using Link component dynamically in React-Router

Depending on a conditional stored in component state, I would like a particular component being rendered to either be wrapped in a Link tag or a regular div tag (or no tag works just as well!)
What I'm currently doing seems verbose and redudnant; I feel like there's a shorter way I could write this component to keep my code DRY.
Both variables storing my linkThumbnail and defaultThumbnnail components are pretty much exactly the same, except for the fact that one of them is contained within a Link component.
I then use a ternary operator in the return statement to give me the desired component.
Here's some pseudocode as an example:
import React, { Component } from "react";
import { Link } from "react-router-dom";
class ExampleComponent extends Component {
state = {
renderLink: false
};
render() {
const linkThumbnail = (
<Link
to={{
pathname: `/someMovieId`,
state: 'some-data'
}}
>
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
</Link>
);
const defaultThumbnail = (
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
);
//here I use a ternary operator to show the correct component...shorter method of doing this?
return this.state.renderLink ? linkThumbnail : defaultThumbnail;
}
}
export default ExampleComponent;
Try creating another component which gets this.state.renderLink as a prop:
const ThumbnailLink = ({enabled, children, ...props}) => {
if (enabled) {
return <Link {...props}>{children}</Link>;
} else {
return <div>{children}</div>;
}
}
class ExampleComponent extends Component {
render() {
return (<ThumbnailLink enabled={this.state.renderLink} to={{pathname: `/someMovieId`, state: 'some-data'}}>
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
</ThumbnailLink>);
}
}

Consuming ReactContext (specifically) Consumers across multiple packages

Context
I created a Context and exported both Producer and Consumer. I am now wrapping my app level example with Producer. I want to be able to consume ContextConsumer inside a module which is served by a different package.
However, when I try to use ContextConsumer inside such module, it throws out the error, cannot call function of undefined.
Code Structure
The below is how I have my code structured.
Context-v1 package
Context.js
import React, { Component, createContext } from 'react';
import PropTypes from 'prop-types';
import ZIndexUtils from './zIndexUtils';
const { node } = PropTypes;
const { Provider, Consumer: IDSContextConsumer } = createContext();
class IDSContextProvider extends Component {
static propTypes = {
children: node.isRequired
};
state = {
topZIndex: ZIndexUtils.getTopZIndex(),
incrementTopZIndex: ZIndexUtils.incrementTopZIndex
};
render() {
return (
<Provider
value={{
topZIndex: this.state.topZIndex,
incrementTopZIndex: this.state.incrementTopZIndex
}}
>
{this.props.children}
</Provider>
);
}
}
export { IDSContextProvider };
export default IDSContextConsumer;
index.js
import IDSContextConsumer, { IDSContextProvider } from './Context';
export {
IDSContextProvider,
IDSContextConsumer
};
Dropdown-v1 package
This component makes use of another component called as Menu-v1 which is where I am trying to use Consumer to access the increment function that I am passing down from app level example.
import { IDSContextConsumer } from '#ids/context-v1';
...
...
render() {
return (
<IDSContextConsumer>
{
(context) => (
<ZIndex assignZIndex getTopZindex={context.incrementTopZIndex}>
<MenuList
className={className}
autoFocus={autoFocus}
aria-label={this.props['aria-label']}
onKeyDown={this.handleKeyDown}
onBlur={this.handleMenuBlur}
reference={reference}
ref={refReactDom}
style={style}
>
{items}
</MenuList>
</ZIndex>
)
}
</IDSContextConsumer>
)
}
App example
Finally, I am trying to use this Dropdown module into my app. Which is where I expect to see the incrementer function be passed in via context.
import { IDSContextProvider } from '#ids/context-v1';
import { Dropdown, MenuItem } from '#ids/dropdown';
render() {
return (
<div>
<IDSContextProvider>
<Modal
open={this.state.openModalDialog}
onCloseModalDialog={this.handleModalClosing}
title="Modal with Dropdown"
>
<Dropdown
onBlur={() => console.log('Dropdown blurrrrr')}
label="Name"
value={this.state.value}
onChange={this.handleDropdownChange}
>
<MenuItem value="1">Banana</MenuItem>
<MenuItem value="2">Apple</MenuItem>
<MenuItem value="3">Guava</MenuItem>
<MenuItem value="4">Mango</MenuItem>
</Dropdown>
</Modal>
</IDSContextProvider>
<button className="divRenderButton" onClick={this.handleModalOpening}>Open Modal</button>
</div>
);
}
Modal component in my example
<Portal>
<Transition
enterClassName={`${prefix}--slideIn`}
transition={open ? transitions.enter : transitions.exit}
onEntered={onShow}
onExited={onClose}
exitClassName={`${prefix}--slideOut`}
unmountOnExit
>
<IDSContextConsumer>
{
(context) => (
<ZIndex
assignZIndex={open}
underlay
getTopZindex={context.incrementTopZIndex}
>
<div
className={open ? 'divContainerWithUnderlay' : ''}
>
{
open &&
<div>
<h1 className="divContent">{title}</h1>
{
this.props.children ? this.props.children : null
}
<button className="divRenderButton" onClick={this.closeModalDialog}>Close Modal</button>
</div>
}
</div>
</ZIndex>
)
}
</IDSContextConsumer>
</Transition>
</Portal>
Requesting earnest help on this. I have tried the solutions from this forum before and cannot find any approach where the modules from different packages share the context.

reactstrap tooltip dynamic id

I am developing a react application and using reactstrap.
I am using Tooltip Component of reactstrap which requires a target attribute, a value of target element's id. This id is being geneated dynamically and seems reactstrap tooltip doesn't like it.
Component looks like:
MovieCard.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Col, Card, CardImg, CardBody, CardTitle, CardSubtitle, CardText, Button, Tooltip } from 'reactstrap';
import { LimitedTextTitle } from '../custom-styled/CustomStyledComponents';
class MovieCard extends Component {
constructor (props) {
super(props);
this.state = {
open: false
};
this.toggle = this.toggle.bind(this);
}
toggle () {
this.setState({
open: !this.state.open
})
}
render () {
const { imdbID, Title, Year, Rated, Plot, Country, Poster } = this.props.movie;
return (
<Col md="4">
<Card>
<CardImg
top
width="100%"
src={Poster}
alt="blah"
/>
</Card>
<CardBody>
<CardTitle>
<LimitedTextTitle id={imdbID}>
{`${Title} - (${Year})`}
</LimitedTextTitle>
<Tooltip placement='top' target={imdbID} isOpen={this.state.open} toggle={this.toggle}>
{Title}
</Tooltip>
</CardTitle>
<CardSubtitle>{`Rated: ${Rated} Country: ${Country}`}</CardSubtitle>
<CardText>{Plot}</CardText>
<Button>Read More</Button>
</CardBody>
</Col>
);
}
}
MovieCard.propTypes = {
movie: PropTypes.object.isRequired // eslint-disable-line
};
export default MovieCard;
Any suggestions?
react vesion 16.2.0
reactstrap 5.0.0-alpha.4
Was dealing with a similar problem.
Adding the code as an answer because i cannot add a comment above...
Hope it will help you or anyone else who will come across this question.
Description:
Use reactstrap tooltip for elements that are getting generated dynamically.
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Button, Tooltip } from 'reactstrap';
class App extends React.Component {
state = {};
toggle = targetName => {
if (!this.state[targetName]) {
this.setState({
...this.state,
[targetName]: {
tooltipOpen: true
}
});
} else {
this.setState({
...this.state,
[targetName]: {
tooltipOpen: !this.state[targetName].tooltipOpen
}
});
}
};
isToolTipOpen = targetName => {
return this.state[targetName] ? this.state[targetName].tooltipOpen : false;
};
render() {
return (
<div>
{[1, 2, 3, 4, 5, 6].map((x, i) => (
<div key={`div-${i}`}>
<Button color="link" id={`btn-${i}`}>
{x}
</Button>
<Tooltip
placement="right"
isOpen={this.isToolTipOpen(`btn-${i}`)}
target={`btn-${i}`}
toggle={() => this.toggle(`btn-${i}`)}>
Hello world!
</Tooltip>
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
react: 16.9.0
reactstrap: 8.0.1
https://codesandbox.io/embed/angry-taussig-fup7i?fontsize=14
EUREKA I GOT IT!!! Building on Meir Keller's answer, there's no need to check if that state for the tooltip already exist. If it doesn't exist, it's false by default...
So long as state is defined, even if it's an empty state, this works.
This is using reactstrap's Popover, but it's the same concept.
import React, { Component, Fragment } from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css'
import { Container, Row, Col, Input, Button, Popover } from 'reactstrap';
class App extends Component {
state = {};
toggle = (target) => {
// console.log(typeof target) // make sure this is a string
this.setState({
...state,
[target]: !this.state[target]
});
};
render() {
return (
<Container>
{["Hello", "Greetings"].map((name) => (
<Row>
<Fragment>
<Button id={name} type="button">{name}</Button>
<Popover placement="right"
isOpen={this.state[`${name}`]}
target={name}
toggle={() => this.toggle(`${name}`)}>
<PopoverBody>
You've got mail. Did you know?
</PopoverBody>
</Popover>
</Fragment>
</Row>
))}
</Container>
);
}
}
export default App;
Create a new component in modular or component directory and paste this code
import React, { useState } from "react";
import { Tooltip } from "reactstrap";
const TooltipItem = props => {
const { position='top', id } = props;
const [tooltipOpen, setTooltipOpen] = useState(false);
const toggle = () => setTooltipOpen(!tooltipOpen);
return (
<span>
<span id={"tooltip-" + id}>
{props.children}
</span>
<Tooltip
placement={position}
isOpen={tooltipOpen}
target={"tooltip-" + id}
toggle={toggle}
>
{props.title}
</Tooltip>
</span>
);
};
export default TooltipItem;
Now import and use this tooltip component
import TooltipItem from "../Tooltip";
<TooltipItem id={'edit' + data.id} title={'Edit Store'}>
<i className="fas fa-edit pointer" onClick={() => this.onEditClick(data)}/>
</TooltipItem>
I will Like to add an answer for it as already many people have mentioned many ways to deal with the problem.
But reactStrap works perfectly fine, mistakes most of the beginners are doing that while creating id they are using special characters like:
- _ / # and it can even be a space
Just keep the id a very simple combination of chars and numbers reactstrap will work totally fine
New component UncontrolledTooltip will solve the problem. Just use
<UncontrolledTooltip
placement="right"
target={`btn-${i}`}
>
{props.title}
</UncontrolledTooltip>
I tried a lot of solutions and was still having trouble with Reactstrap Tooltip crashing when the target element is not in the Dom.
I combined a couple other solutions that people posted and this is the only way it worked for me. Conditional rendering FTW.
const ElementWithTooltip = ({
dynamicIdentifier, // string, number, w/e
}): ReactElement => {
// Target element state.
const [isTargetReady, setIsTargetReady] = useState(false);
// Target element ref.
const tooltipRef = useRef(null);
// Hook to recognize that the target is ready.
useEffect(() => {
const targetElement = tooltipRef.current;
if (targetElement) {
setIsTargetReady(true);
}
}, [tooltipRef.current]);
// TSX.
return (
<>
<span ref={tooltipRef}>This is the target element</span>
{isTargetReady && <UncontrolledTooltip autohide={false} target={tooltipRef}>
Tooltippy text stuff
</UncontrolledTooltip>}
</>
);
The imdbID most probably is starting with digit i.e. 123abcdefghijklmno1234567890
Remember that tooltips can't work in that case when ID starts with a number i.e. the Tooltip's target cannot start with an integer.
all you need to do here is, change this:
<CardTitle>
<LimitedTextTitle id={imdbID}>
{`${Title} - (${Year})`}
</LimitedTextTitle>
<Tooltip placement='top' target={imdbID} isOpen={this.state.open} toggle={this.toggle}>
{Title}
</Tooltip>
</CardTitle>
to this:
<CardTitle>
<LimitedTextTitle id={`movie-${imdbID}`}>
{`${Title} - (${Year})`}
</LimitedTextTitle>
<Tooltip placement='top' target={`movie-${imdbID}`} isOpen={this.state.open} toggle={this.toggle}>
{Title}
</Tooltip>
</CardTitle>
You can avoid using state by simply switching to UncontrolledTooltip which handles all the toggle itself without asking you to handle that explicitly, like:
<CardTitle>
<LimitedTextTitle id={`movie-${imdbID}`}>
{`${Title} - (${Year})`}
</LimitedTextTitle>
<UncontrolledTooltip placement='top' target={`movie-${imdbID}`}>
{Title}
</UncontrolledTooltip>
</CardTitle>
Rendering dynamic content in tooltip in react js is very simple.
Use ReactTooltip.
For full understanding check below example.
Here I am adding requestId in tooltip as dynamically.
{
completedTransactions.map((item, id) => (
<tr key={id + 1}>
<td>{id + 1}</td>
<td>
<span data-tip={item.requestId} data-for="registerTip">
{item.TransactionId}
</span>
<ReactTooltip id="registerTip" place="top" />
</td>
<td>{item.groupName}</td>
<td>{item.purposeName}</td>
<td>{dateFormat(item.update, "dd-mm-yyyy hh:mm tt")}</td>
</tr>
));
}

Material-ui svg-icons inside another element doesnt align to the center

I'm using the material ui library in my react project, and I have come across a strange issue, when I try to use svg icons inside a button-icon, the icom doesn't align to the center.
for example:
<ListItem key={product.id}
primaryText={product.title}
leftAvatar={<Avatar src={product.img}/>}
rightIcon={<IconButton><RemoveIcon/></IconButton>}/>
for this code I will get the following result:
And for this code:
<ListItem key={product.id}
primaryText={product.title}
leftAvatar={<Avatar src={product.img}/>}
rightIcon={<RemoveIcon/>}/>
I will get the following result :
My question is, how do i get to the result of my second example, but that the icon will we inside another element?
This is kind of late but I recently had the same issue and solved it by wrapping the IconButton component in a custom component and extending the css. You may have to change some other CSS to make it align perfectly but this worked for my use case.
import React, { PropTypes, Component } from 'react';
import IconButton from 'material-ui/IconButton';
const CustomIconButton = (props) => {
const { style } = props;
const additionalStyles = {
marginTop: '0'
};
return(
<IconButton {...props } style={{ ...style, ...additionalStyles }} iconStyle={{ fontSize: '20px' }}/>
);
};
CustomIconButton.PropTypes = {
// listed all the props that IconButton requires (check docs)
};
export default PPIconButton;
This is what a simplified usage of this custom IconButton looks like:
const deleteIconButton = (deleteFunc) => {
return <CustomIconButton
touch={true}
tooltip="Delete"
tooltipPosition="top-right"
onTouchTap={deleteFeed}
iconClassName="fa fa-trash"
/>;
};
class MyList extends Component {
render() {
return (
<div>
<List>
<ListItem value={ i } primaryText="My List Item" rightIcon={ deleteIconButton(() => this.props.deleteFeed(i) } />
) }
</List>
</div>
);
}
}
Passing the styles down to the inner element worked for me:
return <SvgIcon style={this.props.style} />
check this code, working fine for me
import React from 'react';
import List from 'material-ui/List';
import ListItem from 'material-ui/List/ListItem';
import Delete from 'material-ui/svg-icons/action/delete';
const MenuExampleIcons = () => (
<div>
<List style={{width:"300px"}}>
<ListItem primaryText="New Config" leftIcon={<Delete />} />
<ListItem primaryText="New Config" rightIcon={<Delete />} />
</List>
</div>
);
export default MenuExampleIcons;

Resources