React - Change size of icon received as props - javascript

I have the following component:
import ListItemButton from '#mui/material/ListItemButton';
import ListItemIcon from '#mui/material/ListItemIcon';
import Tooltip from '#mui/material/Tooltip';
const MenuItem = ({data, onClick}) => {
const menuItemOnClick = () => {
onClick(data);
};
const style = {
display: "flex",
justifyContent: "center",
color: "white",
margin:"auto"
};
return (
<Tooltip title={data.friendlyName} placement="right">
<ListItemButton onClick={menuItemOnClick}>
<ListItemIcon sx={style}>
{data.icon}
</ListItemIcon>
</ListItemButton>
</Tooltip>
);
};
export default MenuItem;
The prop is being passed the following way:
myArray.map(entityTypeData => <MenuItem key={entityTypeData.name} data = {entityTypeData} onClick={onClick} />)
myArray is defined like this:
return [
{
name: "X",
friendlyName: "X",
icon: <MedicationIcon />,
entities: []
},
{
name: "Y",
friendlyName: "Y",
icon: <BiotechIcon />,
entities: []
},
...
];
Further information:
Preferably I want to avoid styling my icon where the array is declared, as this is something for which I want to enforce only when the MenuItem Component is used.
I tried changing the size of the parents, but it doesn't cascade to the child icon.
How can I change the height/width of the icon received as props?

It's very similar of what you already did for styling the <ListItemIcon> but you need to do it on the Icon it self. For example look at the code bellow:
Create the style object:
const iconStyle = {
fontSize: "40px"
};
And in your myArray apply the style using the sx prop
return [
{
name: "X",
friendlyName: "X",
icon: <MedicationIcon sx={iconStyle} />,
entities: []
},
{
name: "Y",
friendlyName: "Y",
icon: <BiotechIcon sx={iconStyle} />,
entities: []
},
...
];
UPDATED
Or based on your comment you can use the existing styling for the <ListItemIcon> like this:
const style = {
display: "flex",
justifyContent: "center",
color: "red",
margin: "auto",
"& svg": {
fontSize: "40px",
}
};
Here is a working codesandbox with an example

Related

Array Map method not rendering properly in React

I am using ChakraUI and React to make a project where I want to show a list of members in the form of cards.
But for some reason the component is not rendering properly. Only the Team member text is showing in the browser. But the part where I mapped the listOfTeamMembers array, is not rendering. What is the reason behind it?
Member component
import { Box, Text, Center, Stack } from "#chakra-ui/layout";
import listOfTeamMembers from "./team-members-list";
function TeamMembers() {
return (
<Box id='team-members' mt={10}>
<Box>
<Center>
<Text fontSize='4xl' as='u' fontFamily='sans-serif'>
Team Members //only this part is showing on website
</Text>
</Center>
<Box>
{listOfTeamMembers.map((items) => {
<Stack
spacing={{ base: "18px", md: "25px", lg: "40px" }}
direction='row'
>
<Box
w={{ base: "300px", md: "200px", lg: "100px" }}
h={{ base: "300px", md: "200px", lg: "100px" }}
borderRadius={5}
>
{items.name}
{items.contact}
{items.details}
</Box>
</Stack>;
})}
</Box>
</Box>
</Box>
);
}
export default TeamMembers;
The member array
const listOfTeamMembers = [
{
name: "Dr. DoofenShmirtz",
contact: "#",
details:
"The evil genius and a loving father of one daughter. Hate Perry the platipus",
},
{
name: "Dr. Frankestein",
contact: "#",
details: "I experiment on Dead People",
},
{
name: "Dr. Drake Ramoray",
contact: "#",
details: "Has magical hands. Can do brain Transplant without any Help",
},
{
name: "Dr. House MD",
contact: "#",
details: "I am a fictional Character. What am I doing here!",
},
{
name: "Dr. Hibbert",
contact: "#",
details: "ohhohohohohohoho",
},
{
name: "Dr. Elmer Hartman",
contact: "#",
details: "My role as a doctor is to cure people. But I do the opposite.",
},
];
export default listOfTeamMembers;
My App.js component
import { ChakraProvider } from "#chakra-ui/provider";
import { useState } from "react";
import Navbar from "../src/components/navbar";
import Home from "./components/Home";
import theme from "./theme";
import TeamMembers from "../src/components/Team Members/team-members";
function App() {
const [isMenuOpen, setIsMenuOpen] = useState(false);
return (
<ChakraProvider theme={theme}>
<Navbar isMenuOpen={isMenuOpen} setIsMenuOpen={setIsMenuOpen} />
<Home isMenuOpen={isMenuOpen} />
<TeamMembers />
</ChakraProvider>
);
}
export default App;
You have to return array item also :-)
{listOfTeamMembers.map((items) => {
return (
<Stack
spacing={{ base: "18px", md: "25px", lg: "40px" }}
direction="row"
>
<Box
w={{ base: "300px", md: "200px", lg: "100px" }}
h={{ base: "300px", md: "200px", lg: "100px" }}
borderRadius={5}
>
{items.name}
{items.contact}
{items.details}
</Box>
</Stack>
);
})}
Here is demo: https://codesandbox.io/s/sharp-ganguly-lcj38?file=/src/App.js:1122-1694

How to use react-i18next when mapping data that comes not from the translation.json

This is the array of objects that I want to map through. As you see, is also contains material-ui icon components. This is why I just can't map through the translation.json in locales
const sidebarData = [
{
text: "Picken",
icon: <GetAppIcon style={{ fontSize: 35 }} />,
path: "/picken",
title: "Artikel picken",
},
{
text: "Hole Artikel",
icon: <AddShoppingCartIcon style={{ fontSize: 35 }} />,
path: "/holeartikel",
title: "Hole Artikel zu dieser Workstation",
},
{
text: "Hole Regal",
icon: <ImportExportIcon style={{ fontSize: 35 }} />,
path: "/holeregal",
title: "Hole Regal zu dieser Workstation",
}];
The locales for the english translation (locales/en/translation.json) looks like that:
{
"sidebarmenu": {
"jobliste": "Joblist",
"picken": "Picken",
"artikel": "Get Item",
"regal": "Get Pod",
"leer": "Get Storage",
"karte": "Show Map"
},
"header": {
"jobliste": "Joblist",
"picken": "Pick Item",
"artikel": "Get Item to this workstation",
"regal": "Get Pod to this workstation",
"leer": "Get empty storage to this workstation",
"karte": "Show Warehouse Map"
}
And the component looks like this:
import React, { useState, useEffect} from "react";
import { useHistory } from "react-router-dom";
import layouttheme from "./layouttheme";
import ListAltIcon from "#material-ui/icons/ListAlt";
import {Drawer,Typography,Divider,ListItemText,ListItem,List,Box,} from "#material-ui/core";
import useStyles from "./LayoutStyles";
import {useTranslation } from "react-i18next";
function DrawerComp({ open, setOpen, sidebarData }) {
const classes = useStyles();
const history = useHistory();
const [getPath, setGetPath] = useState("Jobliste");
const { t } = useTranslation();
function handleClick(item) {
history.push(item.path);
setGetPath(item.title);
}
return (
<Drawer variant="persistent" anchor="left" open={open}>
<List className={classes.sbList} sidebarData={sidebarData}>
{sidebarData.map(item => (
<ListItem
key={item.text}
onClick={() => handleClick(item)}
>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText>{item.text}</ListItemText>
</ListItem>
))}
</List>
</Drawer>
);
}
export default DrawerComp;
So my question is how can connect the sidebarData with the translation.json in order to get the translation?
You can either translate the sidebarData if this object is composed in a parent component:
const sidebarData = [{
text: t("picken"),
icon: <GetAppIcon style={{ fontSize: 35 }} />,
path: "/picken",
title: "Artikel picken",
}, {
text: t("hole_artikel"),
icon: <AddShoppingCartIcon style={{ fontSize: 35 }} />,
path: "/holeartikel",
title: "Hole Artikel zu dieser Workstation",
}, {
text: t("hole_regal"),
icon: <ImportExportIcon style={{ fontSize: 35 }} />,
path: "/holeregal",
title: "Hole Regal zu dieser Workstation",
}];
You can also use the translation keys in the object instead of the full text. Then in your render function, wrap the properties with t().
I personally don't like doing this, since you can't extract the translations with tools like i18next-scanner.
const sidebarData = [{
text: "picken",
icon: <GetAppIcon style={{ fontSize: 35 }} />,
path: "/picken",
title: "Artikel picken",
}, {
text: "hole_artikel",
icon: <AddShoppingCartIcon style={{ fontSize: 35 }} />,
path: "/holeartikel",
title: "Hole Artikel zu dieser Workstation",
}, {
text: "hole_regal",
icon: <ImportExportIcon style={{ fontSize: 35 }} />,
path: "/holeregal",
title: "Hole Regal zu dieser Workstation",
}];
return (
<Drawer variant="persistent" anchor="left" open={open}>
<List className={classes.sbList} sidebarData={sidebarData}>
{sidebarData.map(item => (
<ListItem
key={item.text}
onClick={() => handleClick(item)}
>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText>{t(item.text)}</ListItemText>
</ListItem>
))}
</List>
</Drawer>
);

push to url according to id (reactjs)

new react hooks(typescript) developer here, could somebody suggest on how to implement this: when user has chosen from select option(antd) then the button becomes red and can be clicked, that button should take one to that specific option what he chose (id?) with this?:
history.push(`/info/${....id}`); ??
my code :
import React, { useState } from "react";
import "antd/dist/antd.css";
import { Select } from "antd";
import { useHistory, useRouteMatch } from "react-router-dom";
const { Option } = Select;
const history = useHistory();
function EventsSection() {
const anarray = [
{ name: "obama", address: "usa", id: "81" },
{ name: "obama", address: "usa", id: "86" },
{ name: "putin", address: "russia", id: "91" },
{ name: "erdogan", address: "turkey", id: "31" },
{ name: "jebordoq", address: "alien", id: "29" },
];
return (
<section>
{/* this button becomes red then we know somebody has clicked something from select options */}
<button>if i'm red click me</button>
<Select
className="senderId"
style={{ width: "100%" }}
placeholder="Hide Me"
mode="multiple"
open={true}
listHeight={350}
>
{anarray.map((item, idx) => (
<Option
style={{ width: "100%", height: "100%" }}
className="options"
key={idx}
value={item.id}
>
{item.name}
<br></br>
{item.address}
<br></br>
</Option>
))}
</Select>
</section>
);
}
export default EventsSection;
ask me if needed

How is React Native multiple data input?

My English is not very good, sorry for that. There is a structure that I want to make multiple data entries. I will add separate json lines for each input. But I can add once from the same line. But I want to create a separate json data for each input. I am sharing the sample code. It doesn't work that way because it constantly updates the previous data in.
var families = [];
for(let i = 0; i < formStep + 1; i++) {
families.push(
<View key={i}>
<View>
<Text style={{ marginBottom: 5 }}>T.C</Text>
<Input
placeholder='Lütfen T.C belirtin'
style={{ marginBottom: 10 }}
onChangeText={(input) => this.setState(prevState => ({
formData: [...prevState.formData, {tc: input}]
}))}
/>
</View>
<View>
<Text style={{ marginBottom: 5 }}>İsim</Text>
<Input
placeholder='Lütfen ad ve soyad belirtin'
style={{ marginBottom: 10 }}
/>
</View>
<View>
<Text style={{ marginBottom: 5 }}>Meslek</Text>
<Input
placeholder='Lütfen meslek belirtin'
style={{ marginBottom: 10 }}
/>
</View>
{(formStep > 0) ? <Divider style={{marginBottom: 15, marginTop: 10}}></Divider> : null}
</View>
)
}
working input onChangeText method;
Array [
Object {
"tc": "0",
},
]
Array [
Object {
"tc": "0",
},
Object {
"tc": "00",
},
]
Array [
Object {
"tc": "0",
},
Object {
"tc": "00",
},
Object {
"tc": "000",
},
]
But I want;
Array [
Object {
"tc": "000",
},
]
And then if there is more than one input;
Array [
Object {
"tc": "000",
},
Object {
"tc": "111",
},
Object {
"tc": "222",
},
]
I hope I could tell. Thanks for your help in advance.
If I understand what you want, you just need to overwrite the field you want to update this way:
onChangeText={(input) => this.setState(prevState => ({
formData: [...prevState.formData.tc, {tc: input}]
}))}
And for the other inputs, it would look something like this:
onChangeText={(input) => this.setState(prevState => ({
formData: [...prevState.formData.exemple, {exemple: input}]
}))}
You can also group input changes in one function:
updateText = (key, value) => {
// Merge the old key, or set it
this.setState(currentState => ({
formData: [
...currentState.formData,
[key]: value
]
}));
};
And you use it that way:
onChangeText={text => this.updateText("tc", text)}

How to setState on Object item within array

I want to update state of key heart in the array's objects when the heart icon pressed it changes to red so for this I'm using react native icons and i'm using heart and hearto to switch when click on it
here is the code:
state = {
localAdversiment: [
{
title: "Ecloninear 871",
image: require("../../assets/images/truck_image.png"),
year: "2015",
type: "Truck",
status: "new",
price: "$ 2000",
heart: "hearto"
}
Here it function which is called when heart icon pressed
handleFavourite = index => {
const { heart } = this.state.localAdversiment[index];
this.setState(
{
heart: "heart"
}
);
};
here is the heart icon code
<TouchableOpacity onPress={() => this.handleFavourite(index)}>
<Icon
name={item.heart}
type={"AntDesign"}
style={{ fontSize: 18 }}
/>
</TouchableOpacity>
kindly help me how to update heart as heart instead of hearto when clicked
You can do it easily by following approach
state = {
localAdversiment: [
{
id: 0,
title: "Ecloninear 871",
image: require("../../assets/images/truck_image.png"),
year: "2015",
type: "Truck",
status: "new",
price: "$ 2000",
heart: "hearto",
selected: false
}
}
now in onPress do this
handleFavourite = (item) => {
const { id } = item;
this.setState({
localAdvertisement: this.state.localAdvertisement.map((item) => {
if(item.id === id){
return {
...item,
selected: !item.selected
}
}
return item
})
})
};
Now render like this
<TouchableOpacity onPress={() => this.handleFavourite(item)}>
<Icon
name={item.selected ? "heart" : 'hearto'}
type={"AntDesign"}
style={{ fontSize: 18 }}
/>
</TouchableOpacity>
Hope it will help you
Edit this function as follows:
handleFavourite = index => {
let updatedlocalAdversimentStates = this.state.localAdversiment;
updatedlocalAdversimentStates[index].heart = "heart";
this.setState(
{
localAdversiment: updatedlocalAdversimentStates
}
);
};

Categories