Curly braces as function parameter - javascript

I want to pass emailID as the second parameter to . Can you help me to understand how to pass additional parameter in Curly braces as a function parameter and how to access it in AccountMenuSidebar.
Sorry for asking this basic question.I am a newbie to Javascript and React.
class Invoices extends Component {
render() {
var emailID="guest#somedomain.com";
const accountLinks = [
{
text: 'Account Information',
url: '/account/user-information',
icon: 'icon-user',
},
{
text: 'Notifications',
url: '/account/notifications',
icon: 'icon-alarm-ringing',
},
];
return (
<section className="ps-my-account ps-page--account">
<div className="container">
<div className="row">
<div className="col-lg-4">
<div className="ps-page__left">
<AccountMenuSidebar data={accountLinks} /> // Want to pass email id as second argument here
</div>
</div>
</div>
</div>
</section>
);
}
}
export default Invoices;
const Accountbar = ({ data }) => (
<aside className="ps-widget--account-dashboard">
<p>{email}</p>
<div className="ps-widget__content">
<ul>
{data.map((link) => (
<li key={link.text} className={link.active ? 'active' : ''}>
<Link href={link.url}>
<a>
<i className={link.icon}></i>
{link.text}
</a>
</Link>
</li>
))}
</ul>
</div>
</aside>
);
export default Accountbar;

<AccountMenuSidebar data={accountLinks} email={emailID} />
and
const Accountbar = (data , emaildID) => (...
or
const Accountbar = (props) => (...
and then you can use props like this...
<ul>
{props.data.map((link) => (
<li key={link.text} className={link.active ? 'active' : ''}>
<Link href={link.url}>
<a>
<i className={link.icon}></i>
{link.text}
</a>
</Link>
</li>
))}
</ul>

When you pass the props from Invoices, you usually acces them like this in AccountMenuSidebar:
<AccountMenuSidebar data={accountLinks} />
const AccountMenuSidebar = (props) => {
return (
<p>{props.data}</p>
)
}
However, using destructuring, which lets you directly unpack variables from an object in JavaScript, you can access the props like this instead:
<AccountMenuSidebar data={accountLinks} />
const AccountMenuSidebar = ({ data }) => {
return (
<p>{data}</p>
)
}
So if you want to send another prop, you can access it the same way, i.e.
<AccountMenuSidebar data={accountLinks} email={email} />
const AccountMenuSidebar = (props) => {
return (
<>
<p>{props.data}</p>
<p>{props.email}</p>
</>
)
}
or using destructuring:
<AccountMenuSidebar data={accountLinks} email={email} />
const AccountMenuSidebar = ({ data, email }) => {
return (
<>
<p>{data}</p>
<p>{email}</p>
</>
)
}

Related

Passing selected option's value to another component in nextjs

I'm new to nextjs/react so bare with me here. In my project I have multiple select elements with multiple options in each one. When an option is selected or changed I want to pass that value to another component. I was able to pass an onClick event to another component but when I tried a similar solution I wasn't able to get it to work. So the select elements are being mapped in Component A2, but the options for those elements are also being mapped in Component A3 and I need to pass the value to Component B2. You will see in my code I tried to pass it with the "handleOnChange". I'm not very good at explaining things so here is my code snippets, I hope this makes sense:
Parent Component
export default function Post({ globalProps, page, globalPages, sidebarProps }) {
const [addFlexItem, setAddFlexItem] = useState(false)
const [addFlexItemStyles, setFlexItemStyles] = useState()
return (
<Layout globalProps={globalProps}>
<main className={styles.container}>
<FlexSidebar sidebarProps={sidebarProps} onClick={() => setAddFlexItem(true)} handleOnChange={() => setFlexItemStyles()} />
<FlexContainer addFlexItem={addFlexItem} addFlexItemStyles={addFlexItemStyles} />
</main>
</Layout>
)
}
Component A1
const FlexSidebar = ({ sidebarProps, onClick, handleOnChange }) => {
return (
<aside className={styles.left_sidebar}>
<section className={styles.wrap}>
{/* we are padding the onClick to the child component */}
{container === true && <FlexSidebarContainer sidebarProps={sidebarProps} onClick={onClick} handleOnChange={handleOnChange} />}
{items === true && <FlexSidebarItems sidebarProps={sidebarProps} />}
</section>
</aside>
)
}
Component A2
const FlexSidebarContainer = ({ sidebarProps, onClick, handleOnChange }) => {
const options = sidebarProps.options
return (
<>
<p className={styles.warning}>{sidebarProps.containerWarningText}</p>
<button type="button" className="btn" onClick={() => onClick()}>
{sidebarProps.addItemBtn}
</button>
<form className={styles.form}>
{options.map((option, index) => {
return (
<div key={index} className={styles.form_item}>
<div className={styles.form_label_wrap}>
<label>{option.title}</label>
</div>
<FlexSidebarSelect options={option.items} handleOnChange={handleOnChange} />
</div>
);
})}
</form>
</>
)
}
Component A3
const FlexSidebarSelect = ({ options, handleOnChange }) => {
return (
<div className={styles.form_item_wrap}>
<select onChange={(value) => handleOnChange(value)}>
{options.map((item, index) => {
return (
<option key={index} value={item.value}>{item.item}</option>
)
})}
</select>
</div>
)
}
Component B1
const FlexContainer = ({ addFlexItem, addFlexItemStyles }) => {
return (
<section className={styles.right_content}>
<FlexItem addFlexItem={addFlexItem} addFlexItemStyles={addFlexItemStyles} />
</section>
)
}
Component B2
const FlexItem = ({ addFlexItem, addFlexItemStyles }) => {
const [isaddFlexItem, setaddFlexItem] = useState(addFlexItem)
useEffect(() => {
setaddFlexItem(addFlexItem)
}, [addFlexItem])
return (
isaddFlexItem ?
<div className={styles.flex_item}>
<div className={styles.flex_item_wrap}>
<div className={styles.flex_item_inner}>
</div>
<button className={styles.trash}>
</button>
</div>
</div>
: "empty"
)
}
I will add that if I change the code in Component A3 to this, im able to log the value, but I cant get it to work in the parent component.
const FlexSidebarSelect = ({ options, handleOnChange }) => {
const [value, setValue] = useState("")
const handleOptionChange = (e) => {
let value = e.target.value
setValue({
value
})
}
return (
<div className={styles.form_item_wrap}>
<select onChange={handleOptionChange}>
{options.map((item, index) => {
return (
<option key={index} value={item.value}>{item.item}</option>
)
})}
</select>
</div>
)
}

How to toggle item by id or index ? React.js

I need to opet child component by clicked item. FIrst check code:
<div className="d-flex">
{boardList.map((list) => (
<div className="card m-3 p-3" key={list.id}>
<div className="d-flex flex-column">
<h6> {list.name} </h6>
<ul className="list-group">
{list.cards.map((card) => (
<li className="list-group-item" key={card.id}>
{card.name}
</li>
))}
</ul>
{isVisible ? (
<TodoForm onCloseForm={onCloseForm} />
) : (
<small
className="mt-2"
onClick={showInput}
>
Add new task +
</small>
)}
</div>
</div>
))}
</div>
This is work but when I click on 'Add new task +' a child component opens up to me everywhere. i want only the component with the selected id or index to open.
also component for this :
const [isVisible, setIsVisible] = useState(false);
const [boardList, setBoardList] = useState([]);
useEffect(() => {
axiosInstance
.get("")
.then((res) => {
setBoardList(res.data);
console.log("resp", boardList);
})
.catch((err) => {
console.log(err);
});
}, []);
const showInput = () => {
setIsVisible(true);
};
const onCloseForm = () => {
setIsVisible(false);
};
All the items of the resultant array from boardList.map are depending on the same state isVisible, that's why when you click on one of them all the items mimic the same behaviour.
What you need is to create a component with its own state to encapsulate this part of your code
{isVisible ? (
<TodoForm onCloseForm={onCloseForm} />
) : (
<small
className="mt-2"
onClick={showInput}
>
Add new task +
</small>
)}
This way every instance of this new component would have its own isVisible so they no longer would affect their siblings state.
The component would look like this.
const NewComponent = () => {
const [isVisible, setIsVisible] = useState(false);
return <>
{isVisible ? (
<TodoForm onCloseForm={onCloseForm} />
) : (
<small className="mt-2" onClick={() => setIsVisible(true)}>
Add new task +
</small>
)}
</>
};

How to pass data from one component to another via a function in ReactJS?

How can I pass the data parameter from the openTeam function to another component in another file? The data can't change value, because it has an id in it that can't be changed. I am using functional components in my app.
const openTeam = (data) => {
history.push("/" + data.name)
return (
<div>
</div>
)
}
return (
<div>
<Welcome />
<div>
<ul>
{teams.map((data) => {
return (
<li onClick={() => openTeam(data)} key={data.teamId}>
<h1>{data.name}</h1>
<p>{data.teamId}</p>
</li>
)
})}
</ul>
</div>
</div>
)
}
You can pass data like this to navigated component
const openTeam = (data) => {
this.props.history.push({
pathname: '/',
state: { passedData: data }
})
}
and access like this
this.props.location.state.passedData
Or or similarly for the Link component
<Link to={{
pathname: '/',
state: {passedData: data}
}}> {data.name} </Link>

React App cannot read property 'map' of undefined

I'm a newbie in ReactJS. I'm creating an app that takes from json file data and which is stored in the public folder.
class App extends React.Component {
componentDidMount() {
axios.get('http://localhost:3000/pizza.json').then(data => {
store.dispatch(setPizza(data.Pizza))
})
}
<Route path="/" render = { () => <Main items={ this.props.items }/>} exact></Route>
Also have routing, where on the main page i wanted to display components.
So, I have Item component:
function Item({ image, name, types, sizes, price }) {
const availableTypes = ['0', '1'];
const availableSizes = [26, 30, 40];
const [activeType, setActiveType] = useState(types[0])
const [activeSize, setActiveSize] = useState(sizes[0])
const onSelectType = index => {
setActiveType(index)
}
const onSelectSize = index => {
setActiveSize(index)
}
return (
<div className="item">
<img src={ image } alt="pizza1" className="item-preview"/>
<h3 className="item-name">{ name }</h3>
<div className="item-dimantion">
<ul className="list">
{
availableTypes.map((type, index) => (
<li
key={type}
className={classNames({
choice: true,
active: activeType === index ? 'active' : '',
disable: types.includes(index)
})}
onClick={() => onSelectType(index)}>
{ type }
</li>
))}
</ul>
<ul className="list">
{
availableSizes.map((size, index) => (
<li key={ size }
className={classNames({
choice: true,
active: activeSize === index ? 'active' : '',
disable: sizes.includes(index)
})}
onClick={() => onSelectSize(index)}>
{ size } см.
</li>
))
}
</ul>
</div>
<div className="more">
<h4 className="price">от { price }</h4>
<button className="add">Добавить</button>
</div>
</div>
)
}
Then, I call Item-component in Main:
import { Categories, Sorting, Item } from '../index'
function Main({ items }) {
...
<div className="main__content__items">
{
items.map(obj => {
return (
<Item key={obj}></Item>
)
})
}
</div>
And here I have issue(TypeError: Cannot read property 'map' of undefined), which can not mend for long time... Could you explain me how to fix it?! Thx!!!!
All the code you have posted looks correct. Maybe, you didn't assign value to the items variable.
Try
console.log(this.props.items)
to check whether items are assigned properly. If it's undefined use an empty array.

Creating filter using .map and store

I'm trying to make a filter for my restaurantsAll. The code works without the filter but when I try to add the filter I get this error: TypeError: restaurant.toLowerCase is not a function | Line 25
When I use a:
const list = ['jef', 'uwmoeder'] and list.map
it does work but with the store. it doesn't
Can someone take a look at it please?
<ul>
{store.restaurants.map(restaurant => {
if (filter.lenght !== 0) {
if (restaurant.toLowerCase().startsWith(filter.toLowerCase())) {
return (
<li>
<Restaurant
restaurant={restaurant}
key={restaurant.id}
onClick={() => {
uiStore.setCurrentRestaurant(restaurant);
uiStore.setCurrentView(VIEWS.detail);
}}
/>
</li>
);
} else {
return null;
}
}
return (
<li>
<Restaurant
restaurant={restaurant}
key={restaurant.id}
onClick={() => {
uiStore.setCurrentRestaurant(restaurant);
uiStore.setCurrentView(VIEWS.detail);
}}
/>
</li>
);
})}
</ul>
this is the component Restaurant:
const Restaurant = ({restaurant, onClick}) => {
return useObserver(() => (
<div className={style.restaurantlist} >
<Link to={`/detail/${restaurant.id}`}>
<img onClick={onClick} className={style.restaurantfoto} src={restaurant.picture} alt={restaurant.name} />
</Link>
<section className={style.information}>
<Information restaurant={restaurant} />
</section>
</div>
));
}

Categories