Style Mapped Material-UI Icons with the Same Styles (React) - reactjs

Without adding a className or style tag to each object with a material-ui icon element, what's the best way to style each icon if each icon has the same style?
const btns = [
{ name: "test1", icon: <Icon1 />, link: "test1" },
{ name: "test2", icon: <Icon2 />, link: "test2" },
{
name: "test3",
icon: <Icon3 />,
link: "test3",
},
{ name: "test4", icon: <Icon4 />, link: "test4" },
{ name: "test5", icon: <Icon5 />, link: "test5" },
{ name: "test6", icon: <Icon6 />, link: "test6" },
{ name: "test7", icon: <Icon7 />, link: "test7" },
{ name: "test8", icon: <Icon8 /> },
];
const LeftNav = () => {
const classes = useStyles();
return (
<div className="leftNavContainerStyle">
{btns.map((btn) => {
return (
<Button className={classes.navBtnContainer} color="primary">
{btn.icon} //add the same style to each icon.
{btn.name}
</Button>
);
})}
</div>
);
};
export default LeftNav;
Ive tried changing each icon key to: { name: "test1", icon: Icon1, link: "test1" }, and then changing btn.icon to <btn.icon/> and adding a style like <btn.icon style={styles}/>, but this errors out.
Any help would be appreciated!

You could use the React.cloneElement function and then just pass in the style when it gets cloned. So something like this
{btns.map((btn) => {
return (
<Button className={classes.navBtnContainer} color="primary">
{React.cloneElement(btn.icon, {
// pass in any new props into this object
className={...}
})}
{btn.name}
</Button>
);
})}

Finally figured it out,
import { SvgIcon } from "#material-ui/core"; //import SvgIcon
const btns = [
{ name: "test1", icon: Icon1, link: "test1" },//remove tags from icon components
{ name: "test2", icon: Icon2, link: "test2" },
{
name: "test3",
icon: Icon3,
link: "test3",
},
{ name: "test4", icon: Icon4, link: "test4" },
{ name: "test5", icon: Icon5, link: "test5" },
{ name: "test6", icon: Icon6, link: "test6" },
{ name: "test7", icon: Icon7, link: "test7" },
{ name: "test8", icon: Icon8 },
];
const LeftNav = () => {
const classes = useStyles();
return (
<div className="leftNavContainerStyle">
{btns.map((btn) => {
return (
<Button className={classes.navBtnContainer} color="primary"> //use the component from SvgIcon
<SvgIcon component={btn.icon} className="whateverclassyouwant" />
{btn.name}
</Button>
);
})}
</div>
);
};
export default LeftNav;

Related

With react DnD, why my state resets when every time I drop an element?

I am working on a form builder. The basic implementation works but every time when I move elements from the tool box to the form the current state resets to initial then add newly dropped element so previously dragged element is missed from the form. Below is the linked to the source code at sandbox.
https://codesandbox.io/s/nifty-https-qx8lko
index.js
import Example from "./Example.jsx";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import "./style.sass";
function App() {
return (
<div className="App">
<DndProvider backend={HTML5Backend}>
<Example />
</DndProvider>
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Example.jsx
import React, { useState } from "react";
import Form from "./Form";
import Toolbar from "./Toolbar";
const Example = (props) => {
const [Items, setItems] = useState([{ name: "Test" }]);
const addItem = (item) => {
setItems([...Items, item]);
};
return (
<div className="card" style={{ border: "1px dashed rgb(219 163 163)" }}>
<div className="card-header d-flex justify-content-between">
<h5 className="cart-title m-0">View</h5>
</div>
<div className="card-body">
<div className="row">
<div className="col-9">
<Form items={Items} addItems={addItem} />
</div>
<div className="col-3">
<Toolbar />
</div>
</div>
</div>
</div>
);
};
export default Example;
Form.jsx
import React from "react";
import { useDrop } from "react-dnd";
import { ItemTypes } from "./ItemTypes";
function Form(props) {
const addItem = (item) => {
props.addItems(item);
};
const [{ canDrop, isOver }, drop] = useDrop(() => ({
accept: ItemTypes.CARD,
drop: (item, monitor) => addItem(item),
collect: (monitor) => ({
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
})
}));
return (
<div className="card card-default shadow-sm mt-3">
<div className="card-body">
{props.items.map((item, index) => {
return (
<div key={index} className="form-item">
{item.name}
</div>
);
})}
<div ref={drop}>
{/* {canDrop ? "Release to drop" : "Drag a box here"} */}
{isOver && canDrop && (
<div className="form-place-holder">
<div>Release to Drop</div>
</div>
)}
{!isOver && (
<div className="form-place-holder">
<div>Dropzone</div>
</div>
)}
</div>
</div>
</div>
);
}
export default Form;
Toolbar.jsx
import React from "react";
import ToolbarItem from "./ToolbarItem";
const Toolbar = () => {
const _defaultItems = () => {
return [
{
key: "Header",
name: "Header Text",
icon: "fas fa-heading",
static: true,
content: "Place holder text"
},
{
key: "Label",
name: "Label",
static: true,
icon: "fas fa-font",
content: "Place holder text"
},
{
key: "Paragraph",
name: "Paragraph",
static: true,
icon: "fas fa-paragraph",
content: "Place holder text"
},
{
key: "LineBreak",
name: "Line break",
static: true,
icon: "fas fa-arrows-alt-h"
},
{
key: "Dropdown",
canHaveAnswer: true,
name: "Dropdown",
icon: "far fa-caret-square-down",
label: "Place holder label",
field_name: "dropdown_",
options: []
},
{
key: "Tags",
canHaveAnswer: true,
name: "Tags",
icon: "fas fa-tags",
label: "Place holder label",
field_name: "tags_",
options: []
},
{
key: "Checkboxes",
canHaveAnswer: true,
name: "Checkboxes",
icon: "far fa-check-square",
label: "Place holder label",
field_name: "checkboxes_",
options: []
},
{
key: "RadioButtons",
canHaveAnswer: true,
name: "Multiple choices",
icon: "far fa-dot-circle",
label: "Place holder label",
field_name: "radiobuttons_",
options: []
},
{
key: "TextInput",
canHaveAnswer: true,
name: "Text input",
label: "Place holder label",
icon: "fas fa-font",
field_name: "text_input_"
},
{
key: "NumberInput",
canHaveAnswer: true,
name: "Number input",
label: "Place holder label",
icon: "fas fa-plus",
field_name: "number_input_"
},
{
key: "TextArea",
canHaveAnswer: true,
name: "Multi line input",
label: "Place holder label",
icon: "fas fa-text-height",
field_name: "text_area_"
},
{
key: "TwoColumnRow",
canHaveAnswer: false,
name: "Two columns row",
label: "",
icon: "fas fa-columns",
field_name: "two_col_row_"
},
{
key: "ThreeColumnRow",
canHaveAnswer: false,
name: "Three columns row",
label: "",
icon: "fas fa-columns",
field_name: "three_col_row_"
},
{
key: "FourColumnRow",
canHaveAnswer: false,
name: "Four columns row",
label: "",
icon: "fas fa-columns",
field_name: "four_col_row_"
},
{
key: "Image",
name: "Image",
label: "",
icon: "far fa-image",
field_name: "image_",
src: ""
},
{
key: "Rating",
canHaveAnswer: true,
name: "Rating",
label: "Place holder label",
icon: "fas fa-star",
field_name: "rating_"
},
{
key: "DatePicker",
canDefaultToday: true,
canReadOnly: true,
dateFormat: "MM/dd/yyyy",
timeFormat: "hh:mm aa",
showTimeSelect: false,
showTimeSelectOnly: false,
showTimeInput: false,
name: "Date",
icon: "far fa-calendar-alt",
label: "Place holder label",
field_name: "date_picker_"
},
{
key: "Signature",
canReadOnly: true,
name: "Signature",
icon: "fas fa-pen-square",
label: "Signature",
field_name: "signature_"
},
{
key: "HyperLink",
name: "Website",
icon: "fas fa-link",
static: true,
content: "Place holder website link",
href: "http://www.example.com"
},
{
key: "Download",
name: "File attachment",
icon: "fas fa-file",
static: true,
content: "Place holder file name",
field_name: "download_",
file_path: "",
_href: ""
},
{
key: "Range",
name: "Range",
icon: "fas fa-sliders-h",
label: "Place holder label",
field_name: "range_",
step: 1,
default_value: 3,
min_value: 1,
max_value: 5,
min_label: "Easy",
max_label: "Difficult"
},
{
key: "Camera",
name: "Camera",
icon: "fas fa-camera",
label: "Place holder label",
field_name: "camera_"
},
{
key: "FileUpload",
name: "File upload",
icon: "fas fa-file",
label: "Place holder label",
field_name: "file_upload_"
}
];
};
return (
<div className="react-form-builder-toolbar">
<h4>Toolbox</h4>
<ul>
{_defaultItems().map((item, index) => {
return <ToolbarItem data={item} key={index} />;
})}
</ul>
</div>
);
};
export default Toolbar;
ToolbarItem.jsx
import React from "react";
import { useDrag } from "react-dnd";
import { ItemTypes } from "./ItemTypes";
function ToolbarItem(props) {
const data = props.data;
const [{ isDragging }, drag, dragPreview] = useDrag(() => ({
type: ItemTypes.CARD,
collect: (monitor) => ({
isDragging: monitor.isDragging()
}),
item: props.data
}));
return (
<li ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
<i className={data.icon}></i>
{data.name}
</li>
);
}
export default ToolbarItem;
I have tried also storing the state in redux and still same behavior. For simplicity I have kept the state in parent component in Sandbox example.
In Example.js file try replacing with this setItems((items)=>[...items, item]);
I think this will fix the issue. Check this here https://codesandbox.io/s/reactjs-dnd-example-forked-1lu5i9?file=/src/Form.jsx

How to set json data to footer list react

I start working with react and i need to set mock json data to list in footer.
How i can set list dynamically to each module. I have 3 modules Company, Catalog, Contacts, and JSON:
const FOOTER_DATA = {
menu: {
title: "Company",
items: [
{
title: "Link 1",
link: "#",
},
{
title: "Link 2",
link: "#",
}
],
},
catalog: {
title: "Catalog",
items: [
{
title: "Link Link 1",
link: "#",
},
{
title: "LinkLink 2",
link: "#",
},
{
title: "LinkLink 3",
link: "#",
},
{
title: "LinkLink 4",
link: "#",
},
{
title: "LinkLink 5",
link: "#",
},
{
title: "LinkLink 6",
link: "#",
}
],
},
contact: {
email: "some-mail#gmail.com",
tel: "777 777 777",
work_time: {
weekdays: "09:00 - 18:00",
weekends: "10:00 - 16:00",
},
},
};
How i can set this for each jsx file, to special tags:
<Company />
<Categories />
<Contacts />
I am really beginner in react an i stuck in such issues.
You should pass the data as a prop to each element and render the data inside each component.
<Company data={FOOTER_DATA?.menu}/>
<Categories data={FOOTER_DATA?.catalog}/>
<Contacts data={FOOTER_DATA?.contact}/>
For example you may have a JSX component for Company like below,
import React from "react";
const Company = ({ data }) => {
return (
<React.Fragment>
<h2>{data.title}</h2>
{data.items.map((item, index) => (
<a key={index} href={item.link}>
{item.title}
</a>
))}
</React.Fragment>
);
};
export default Company;

React.js: Customize sidebar menu based on API response

I'm trying to customize the sidebar navigation menu of my app based on a JSON response
The concept I'm trying to pattern my code to is using React Context and React Hooks
From my Header.js (which is my top navigation)
import {
useUserDispatch,
customizeSidebar
} from "../../context/UserContext";
var userDispatch = useUserDispatch();
useEffect(() => {
if( selectedProduct.trim() == "remittance" ){
setIsRemLabelHidden(true)
} else if( selectedProduct == "inward" ){
customizeSidebar(userDispatch, "91454020-C1AC-446C-A1CA-C68F6FDBB053", props.history)
setIsRemLabelHidden(false)
}
}, [selectedProduct]);
I trigger customizeSidebar function which is found in my UserContext.js
export {
UserProvider,
useUserState,
useUserDispatch,
customizeSidebar,
};
function customizeSidebar(dispatch, profileId, history){
ProfileMaintenanceService.retrieveProfileDetails(profileId)
.then((response) => {
console.log("customizeSidebar response.data ", response.data)
}).catch((err) => {
// check first if api is down
console.log("customizeSidebar - catch err.response.data >>> ", err.response.data)
})
}
As seen above, I can now get the JSON response in the then statement.
My question would be, how do I pass the JSON response, for instance I saved it in a state. How do I pass it to other component?
Specifically in my Sidebar.js
import React, { useState, useEffect } from "react";
import { Drawer, IconButton, List } from "#material-ui/core";
import {
SwapHoriz as SwapHorizIcon,
Inbox as InboxIcon,
PresentToAll as PresentToAllIcon,
Help as HelpIcon,
ListAlt as ListAltIcon,
Language as LanguageIcon,
Description as DescriptionIcon,
List as ListIcon,
Money as MoneyIcon,
Face as FaceIcon,
TransferWithinAStation as TransferWithinAStationIcon,
AttachMoney as AttachMoneyIcon,
PersonPinCircle as PersonPinCircleIcon,
Home as HomeIcon,
ArrowBack as ArrowBackIcon,
Edit as EditIcon
} from "#material-ui/icons";
import { useTheme } from "#material-ui/styles";
import { withRouter } from "react-router-dom";
import classNames from "classnames";
import useStyles from "./styles";
import SidebarLink from "./components/SidebarLink/SidebarLink";
import {
useLayoutState,
useLayoutDispatch,
toggleSidebar
} from "../../context/LayoutContext";
import Dot from "./components/Dot";
function Sidebar({ location }) {
var classes = useStyles();
var theme = useTheme();
var { isSidebarOpened } = useLayoutState();
var layoutDispatch = useLayoutDispatch();
var [isPermanent, setPermanent] = useState(true);
var structure = [
{ id: 0,
label: "Dashboard",
link: "/app/dashboard",
icon: <HomeIcon /> },
{
id: 1,
label: "Inward",
link: "/app/inward",
icon: <InboxIcon />,
children: [
{ label: "PESONet", link: "/app/inward/pesonet", icon: <Dot size="small" color="primary" /> },
{ label: "PESONet Inquiry", link: "/app/inward/pesonetinquiry", icon: <Dot size="small" color="primary" /> },
{ label: "PDDTS", link: "/app/inward/pddts", icon: <Dot size="small" color="primary" /> },
// { label: "PDDTS Inquiry", link: "/app/inward/pddtsinquiry" },
{ label: "SWIFT", link: "/app/inward/swift", icon: <Dot size="small" color="primary" /> },
// { label: "SWIFT Inquiry", link: "/app/inward/swiftinquiry" },
{ label: "Philpass", link: "/app/inward/philpass", icon: <Dot size="small" color="primary" /> },
],
},
// {
// id: 2,
// label: "Outward",
// link: "/app/outward",
// icon: <PresentToAllIcon />,
// children: [
// { label: "Inward", link: "/app/transfers/inward", icon: <InboxIcon /> },
// { label: "Outward", link: "/app/transfers/outward", icon: <PresentToAllIcon /> },
// ],
// },
{ id: 3, type: "divider" },
{
id: 4,
label: "Proof List",
link: "/app/prooflist",
icon: <ListAltIcon />,
children: [
{ label: "Proof Web", link: "/app/prooflist/web", icon: <LanguageIcon /> },
{ label: "Proof Others", link: "/app/prooflist/others", icon: <ListIcon /> },
],
},
{ id: 5, label: "Miscellaneous", link: "/app/misc", icon: <DescriptionIcon /> },
{
id: 6,
label: "RPS",
link: "/app/rps",
icon: <MoneyIcon />,
children: [
{ label: "Client Maintenance", link: "/app/rps/clientmaintenance", icon: <FaceIcon /> },
{ label: "Process SFTP", link: "/app/rps/sftp", icon: <TransferWithinAStationIcon /> },
{ label: "Process PESONet", link: "/app/rps/pesonet", icon: <AttachMoneyIcon /> },
{ label: "Override Enrollment", link: "/app/rps/overrideenrollment", icon: <PersonPinCircleIcon /> },
],
},
{ id: 7, label: "Message Converter", link: "/app/message", icon: <EditIcon /> },
];
useEffect(function() {
window.addEventListener("resize", handleWindowWidthChange);
handleWindowWidthChange();
return function cleanup() {
window.removeEventListener("resize", handleWindowWidthChange);
};
});
return (
<Drawer
variant={isPermanent ? "permanent" : "temporary"}
className={classNames(classes.drawer, {
[classes.drawerOpen]: isSidebarOpened,
[classes.drawerClose]: !isSidebarOpened,
})}
classes={{
paper: classNames({
[classes.drawerOpen]: isSidebarOpened,
[classes.drawerClose]: !isSidebarOpened,
}),
}}
open={isSidebarOpened}
>
<div className={classes.toolbar} />
<div className={classes.mobileBackButton}>
<IconButton onClick={() => toggleSidebar(layoutDispatch)}>
<ArrowBackIcon
classes={{
root: classNames(classes.headerIcon, classes.headerIconCollapse),
}}
/>
</IconButton>
</div>
<List className={classes.sidebarList}>
{structure.map(link => (
<SidebarLink
key={link.id}
location={location}
isSidebarOpened={isSidebarOpened}
{...link}
/>
))}
</List>
</Drawer>
);
function handleWindowWidthChange() {
var windowWidth = window.innerWidth;
var breakpointWidth = theme.breakpoints.values.md;
var isSmallScreen = windowWidth < breakpointWidth;
if (isSmallScreen && isPermanent) {
setPermanent(false);
} else if (!isSmallScreen && !isPermanent) {
setPermanent(true);
}
}
}
export default withRouter(Sidebar);
Also, should I save the json data on the state? Or on the context. If on the context, how?
Thanks in advance for those who would help.
Try this
use state. Make the customizeSidebar return the response, and call this kind of code in your SideBar component :
const [sideBar, setSideBar] = useState({})
useEffect(() => {
const sidebar = customizeSidebar()
setSideBar(sidebar)
}, [])
then below the code call your sidebar using the sideBar state, the sideBar will re-render with the new sidebar responded.
also maybe you want to put a loading animation while waiting for the sidebar result. I don't get the idea why you need to put it in context but the solution should works IMO.

TypeScript: Property 'icon' does not exist on type 'JSX.IntrinsicElements'

Hello I'm trying to use typescript with react-icons as follows:
import { IconType } from 'react-icons';
import { FiAlertOctagon } from 'react-icons/fi';
export interface IDropdownItems {
name: string;
link: string;
}
export interface ITag {
name: string;
link: string;
icon: IconType;
dropdownItems: IDropdownItems[] | null;
active: boolean;
}
export const SideBarTags: ITag[] = [
{
name: 'Tutoriais',
link: '../tutorials',
icon: FiAlertOctagon,
dropdownItems: null,
active: false,
},
{
name: 'Avisos',
link: '../news',
icon: FiAlertOctagon,
dropdownItems: null,
active: false,
},
{
name: 'Serviços',
link: '../services',
icon: FiAlertOctagon,
active: false,
dropdownItems: [
{ name: 'Elo Boost', link: '/eloBost' },
{ name: 'Duo Boost', link: '/duoBoost' },
{ name: 'MD10', link: '/eloBost' },
{ name: 'Coaching', link: '/duoBoost' },
{ name: 'Vitóriais', link: '/duoBoost' },
],
},
{
name: 'Carteira',
link: '../cartcredit',
icon: FiAlertOctagon,
active: false,
dropdownItems: [
{ name: 'Histórico', link: '/history' },
{ name: 'Adicionar Crédito', link: '/add' },
],
},
];
and did the following in tsx:
<a>
<icon />
<span className="li-name">{name}</span>
</a>
but i got this erros:
Property 'icon' does not exist on type 'JSX.IntrinsicElements'.
TS2339
I can't seem to find the right way to do this
I'm not able to find the correct way to do this, how I could pass an icon or its name through my array and render in tsx
In JSX, lower case tags are used for the built in elements like <div> <a> or <span>, and it's complaining that <icon> is not one of those. For custom components, you need to use an upper case letter. If you're receive a prop that's in lower case that's fine, but you'll need to rename it before using it for a jsx tag. For example:
const Example = (props) => {
const Icon = props.icon;
return (
<a>
<Icon />
<span className="li-name">{name}</span>
</a>
)
}

How to show selected item in list with a different color in react native using native base ui kit?

I want to show the sidebar content in a different background color.For that I've tried TouchableOpacity underlay.But that is not the one I'm looking for.After giving TouchableOpacity ,it will change the color of the text only not the entire list background.How do I change the listitem background color as I'm using native base ui kit.Please help.Is there any method to do that?This is how the sidebar looks like.I've done something likes the following.Setting pressStatus as true within onPresList and if it is true change backround color.But navigation to route is not working.There is a mistake
https://i.stack.imgur.com/w9YiR.png
How do I change background color onPress? Following is my code.
updated
import React, { Component } from "react";
import { Image, FlatList } from "react-native";
import {
Content,
Text,
List,
ListItem,
Icon,
Container,
Left,
Right,
Badge,
Thumbnail
} from "native-base";
import styles from "./style";
const drawerCover = require("../../imgs/quwait.jpg");
const datas = [
{
name: "Dashboard",
route: "Anatomy",
icon: require("../../imgs/dashboard.png"),
},
{
name: "Companies",
route: "Header",
icon: require("../../imgs/enterprise1.png"),
},
{
name: "Company Admin",
route: "Footer",
icon: require("../../imgs/icon1.png"),
},
{
name: "Employee",
route: "NHBadge",
icon: require("../../imgs/businessman1.png"),
},
{
name: "Employs",
route: "NHButton",
icon: require("../../imgs/employee1.png"),
},
{
name: "Announcement",
route: "NHCard",
icon: require("../../imgs/megaphone1.png"),
},
{
name: "Holiday",
route: "Check",
icon: require("../../imgs/sun-umbrella1.png"),
},
{
name: "Accounting Report",
route: "NHTypography",
icon: require("../../imgs/accounting1.png"),
},
{
name: "Invoice",
route: "NHCheckbox",
icon: require('../../imgs/approve-invoice1.png'),
},
{
name: "Settings",
route: "NHDatePicker",
icon: require('../../imgs/settings1.png'),
},
{
name: "Safety Phone Numbers",
route: "NHThumbnail",
icon: "user",
},
{
name: "NBK",
route: "NHDeckSwiper",
icon: "swap",
},
{
name: "ABK",
route: "NHFab",
icon: "help-buoy",
},
{
name: "CBK",
route: "NHForm",
icon: "call",
},
{
name: "Daily Invoice",
route: "NHIcon",
icon: "information-circle",
},
{
name: "Kolin",
route: "NHLayout",
icon: "grid",
},
{
name: "Limak",
route: "NHList",
icon: "lock",
},
{
name: "Polaytol",
route: "ListSwipe",
icon: "code-working",
},
{
name: "ACTS",
route: "NHPicker",
icon: "arrow-dropdown",
}
];
class SideBar extends Component {
constructor(props) {
super(props);
this.state = {
shadowOffsetWidth: 1,
shadowRadius: 4,
pressStatus:false
};
}
onPressList = (DATA, INDEX) => {
this.props.navigation.navigate(DATA.route);
this.setState({ pressStatus : true, selectedItem: INDEX});
}
render() {
return (
<Container>
<Content
bounces={false}
style={{ flex: 1, backgroundColor: "#fff", top: -1 }}
>
<Image source={drawerCover} style={styles.drawerCover} />
<FlatList
data={datas}
keyExtractor={(item, index) => String(index)}
renderItem={({ DATA, INDEX }) => {
<ListItem
button
noBorder
onPress={() => this.onPressList(DATA, INDEX)}
style={{
backgroundColor:
this.state.selectedItem === INDEX ? "#cde1f9" : "transparent"
}}
>
<Left>
<Image
source={DATA.icon }
style={{width:30,height:30}}
/>
<Text style={styles.text}>
{DATA.name}
</Text>
</Left>
</ListItem>}}
/>
</Content>
</Container>
);
}
}
export default SideBar;
In the App example from native Base they don't support styles for background items list. So you should change your List component from NativeBase and add a FlatList Component from react native. But you should also return the ListItem component from NativeBase and don't forget the import { FlatList } from "react-native";
You should also modify the onPressList function (I would transform it into an arrow function)
In your states you need to add the state selectedItem: 0
Everytime you press an item, your function would be called by modifying a selectedItem idex, which tells the Flatlist, which Item should get which background. I think this has to be the solution.
If it doesn't compile, make sure that you support arrow functions and that any curly braces or something like that isn't missing.
Final Code UPDATE
import React, { Component } from "react";
import { Image, FlatList } from "react-native";
import {
Content,
Text,
List,
ListItem,
Icon,
Container,
Left,
Right,
Badge,
Thumbnail
} from "native-base";
import styles from "./style";
const drawerCover = require("../../imgs/quwait.jpg");
const datas = [
{
name: "Dashboard",
route: "Anatomy",
icon: require("../../imgs/dashboard.png"),
},
{
name: "Companies",
route: "Header",
icon: require("../../imgs/enterprise1.png"),
},
{
name: "Company Admin",
route: "Footer",
icon: require("../../imgs/icon1.png"),
},
{
name: "Employee",
route: "NHBadge",
icon: require("../../imgs/businessman1.png"),
},
{
name: "Employs",
route: "NHButton",
icon: require("../../imgs/employee1.png"),
},
{
name: "Announcement",
route: "NHCard",
icon: require("../../imgs/megaphone1.png"),
},
{
name: "Holiday",
route: "Check",
icon: require("../../imgs/sun-umbrella1.png"),
},
{
name: "Accounting Report",
route: "NHTypography",
icon: require("../../imgs/accounting1.png"),
},
{
name: "Invoice",
route: "NHCheckbox",
icon: require('../../imgs/approve-invoice1.png'),
},
{
name: "Settings",
route: "NHDatePicker",
icon: require('../../imgs/settings1.png'),
},
{
name: "Safety Phone Numbers",
route: "NHThumbnail",
icon: "user",
},
{
name: "NBK",
route: "NHDeckSwiper",
icon: "swap",
},
{
name: "ABK",
route: "NHFab",
icon: "help-buoy",
},
{
name: "CBK",
route: "NHForm",
icon: "call",
},
{
name: "Daily Invoice",
route: "NHIcon",
icon: "information-circle",
},
{
name: "Kolin",
route: "NHLayout",
icon: "grid",
},
{
name: "Limak",
route: "NHList",
icon: "lock",
},
{
name: "Polaytol",
route: "ListSwipe",
icon: "code-working",
},
{
name: "ACTS",
route: "NHPicker",
icon: "arrow-dropdown",
}
];
class SideBar extends Component {
constructor(props) {
super(props);
this.state = {
shadowOffsetWidth: 1,
shadowRadius: 4,
pressStatus:false,
selectedItem:0
};
}
onPressList = (data, index) => {
this.props.navigation.navigate(data.route);
this.setState({ pressStatus : true, selectedItem: index});
}
render() {
return (
<Container>
<Content
bounces={false}
style={{ flex: 1, backgroundColor: "#fff", top: -1 }}
>
<Image source={drawerCover} style={styles.drawerCover} />
<FlatList
data={datas}
keyExtractor={(item, index) => String(index)}
extraData={this.state.selectedItem}
renderItem={({item:data, index}) => {
const { selectedItem: sd } = this.state
const localColor ={backgroundColor: sd === index ? "#cde1f9" : "transparent"}
return (
<ListItem
button
noBorder
style={localColor}
onPress={() => this.onPressList(data, index)}
>
<Left>
<Image
source={data.icon}
style={{width:30,height:30}}
/>
<Text style={styles.text}>
{data.name}
</Text>
</Left>
</ListItem>
)
}}
/>
</Content>
</Container>
);
}
}
export default SideBar;

Resources