I m trying to use a "if" statement but it doesnt run - reactjs

I have this components
and i have this code as the if sentence.
I have the same method in other project that works, can anyone help?
it should only render the first one as addnewchat hte others ones should be avatars, if i take of the "!" only renders the avatars.

You can change the syntax of if and else. Instead of using ternary operator directly after return keyword, use a parent tag, and then wrap your whole component inside it. Like
return (
<>
{addNewChat ? (
<div>if logic here</div>
) : (
<div>else logic here</div>
)}
</>
)

calling component:
<div className="sidebar__chats">
<SidebarChat addNewChat />
<SidebarChat />
<SidebarChat />
<SidebarChat />
<SidebarChat />
</div>
code:
return (
<>
{addNewChat ? (
<div className="sidebarChat">
<Avatar
alt="João Espinheira"
src={`https://avatars.dicebear.com/api/pixel-art/${seed}.svg`}
sx={{ width: 38, height: 38 }}
/>
<div className="sidebarChat__info">
<h2>room name</h2>
<p>last message...</p>
</div>
</div>
) : (
<div onClick={createChat} className="sidebarChat">
<h2>add new chat</h2>
</div>
)}
</>
);
}
i think the code should work, no?

function SidebarChat({ id, name, addNewChat }) like this works fine!
previously i had left a part the {} so that was the thing it was missing

Related

React error: "Each child in a list should have a unique "key" prop."

Hi I am getting an error that says "each child in a list should have a unique "key" prop. When I check the Components using React Developer Tools I don't see any duplicates - what am I doing wrong?
return (
<>
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
>
{ modalIsOpen ? (
<Note
key={'ModalNote' + modalNote.id}
id={modalNote.id}
title={modalNote.title}
text={modalNote.text}
date={modalNote.date}
deleteNote={deleteNote}
closeNote={closeModal}
/>
) : ('')
}
</Modal>
<div className="notesForm">
<AddNote addNoteHandler={addNoteHandler}/>
</div>
<div className="notes">
{notes.map((note) => (
<>
<Note
key={note.id}
id={note.id}
title={note.title}
text={note.text}
date={note.date}
deleteNote={deleteNote}
closeNote={closeModal}
openModal={openModal}
modalIsOpen={modalIsOpen}
/>
</>
))}
</div>
</>
);
Try this, Instead of Fragment add div, It might works.
-> And if You want Fragment then:
<React.Fragment key={note.id}>
<div key={note.id}>
<Note
key={note.id}
id={note.id}
title={note.title}
text={note.text}
date={note.date}
deleteNote={deleteNote}
closeNote={closeModal}
openModal={openModal}
modalIsOpen={modalIsOpen}
/>
</div>
The keys are to be added to the outermost element returned from the map
Here in your e.g its the fragment <>, to add the key to the fragment you should be using <React.Fragment> for shorthand as shorter syntax doesn't support keys
{notes.map((note) => (
<React.Fragment key={note.id}>
<Note
key={note.id}
id={note.id}
title={note.title}
text={note.text}
date={note.date}
deleteNote={deleteNote}
closeNote={closeModal}
openModal={openModal}
modalIsOpen={modalIsOpen}
/>
</React.Fragment>
))}
These other answers are fine, but to ensure every key is unique do not use a numerical key. It's better to use a combination of text and numbers for your keys or, even better, a short id - https://www.npmjs.com/package/shortid
<Note
key={`note-${note.id}`}
id={note.id}
title={note.title}
/>
https://reactjs.org/docs/lists-and-keys.html#keys

Fabric UI Using PivotItem in Map Loop

I'm trying to dynamically add PivotItems to a Fabric UI Pivot.
return (
<div>
<PrimaryButton style={{margin:5 }} onClick={addItem}>
Add
</PrimaryButton>
<Pivot aria-label="My Items">
{items.map((item)=>{
return (
<div key={uniqueId}>
<PivotItem headerText="test">
Test
</PivotItem>
</div>)
})}
</Pivot>
</div>
)
but the items are not rendering.
When I remove all the Pivot/item-stuff and just print out some text it works fine...
ok I finally found the issue here.
Inside the map-function I used
<div key...
but this code is inside a <pivot> which allows only <PivotItem> as childs...
so I fixed it like this and it works:
return (
<div>
<PrimaryButton style={{margin:5 }} onClick={addItem}>
Add
</PrimaryButton>
<Pivot aria-label="My Items">
{items.map((item)=>{
return (
<PivotItem headerText="test" key={uniqueId}>
Test
</PivotItem>
)
})}
</Pivot>
</div>
)

Put linebreak between components rendered with .map and boostrap

I´m rendering an array, every element of the array is showed with component "Post", but the elements are in the same line, I tried with
return (
<div style={{ height: 'calc(100vh - 65px)' }} className="d-flex justify-content-center align-items-center">
{posts.map((post) => {
return <Post key={post._id} post={post} />
})}
</div>
);
The component "Post" is the next:
I´m using Boostrap por the css styles
return (
{usuario.nombre}
Special title treatment
{texto}
Go somewhere
2 days ago
);
My result (All the elements are in horizontal position and I need them in vertical position):
The father component is root.
If I delete the css classes of the component "Post", teh problem remains.
Have you tried this.
return (
<div>
{posts.map((post) => {
return <><Post key={post._id} post={post} /><br /></>
})}
</div>
);
I only changed the class of div where I put the .map ;| adn the problem was solved.
className="container" instead className="d-flex justify-content-center align-items-center">

Parsing error in React class Component while using condition

I get this Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>? error while everything in my Component is set up correctly. I have double-cheked everything and there seems to be nothing wrong. Collapse component is highlighted in error message. What have i done wrong or what could cause error here?
Code part with error:
return (
<div>
{
isAuthenticatedAndIsCoach ?
<h2>Lisa</h2>
<Collapse defaultActiveKey={['0']} onChange={callback} style={{ marginBottom: '10px', borderRadius: '10px'}}>
<Panel header="Valige treeningu asukoht kaardilt" key="1">
<Map />
</Panel>
</Collapse>
<CustomForm
requestType="post"
trainingID={null}
btnText="Loo treening"/>
: <span>Teil puudub vastav luba postitamiseks</span>
}
</div>
)
You should wrap JSX returned by ternary condition with React.Fragment (or <>) as React expects a single element each time a render function is executed.
https://en.reactjs.org/docs/fragments.html
return (
<div>
{isAuthenticatedAndIsCoach ? (
<>
<h2>Lisa</h2>
<Collapse
defaultActiveKey={["0"]}
onChange={callback}
style={{ marginBottom: "10px", borderRadius: "10px" }}
>
<Panel header="Valige treeningu asukoht kaardilt" key="1">
<Map />
</Panel>
</Collapse>
<CustomForm
requestType="post"
trainingID={null}
btnText="Loo treening"
/>
</>
) : (
<span>Teil puudub vastav luba postitamiseks</span>
)}
</div>
);

Getting warning about unique "key" when trying to import ReactCSSTransitionGroup into react app

I hope somebody could shed some light into this issue. After many attempts, I was able to import ReactCSSTransitionGroup into my react app correctly. Now I'm getting the following warning and my transition is not working.
Warning: Each child in an array or iterator should have a unique "key" prop.
I wrapped my component in the main App.js file with the ReactCSSTransitionGroup element like this.
return (
<div className="container">
<Navigation />
<div className="app-items-container">
{
this.state.notes.map((note) => {
return(
<ReactCSSTransitionGroup {...transitionOptions}>
<Note noteContent={note.noteContent}
noteId={note.id}
key={note.id}
removeNote={this.removeNote} />
</ReactCSSTransitionGroup>
)
})
}
</div>
<Form addNote={this.addNote} />
</div>
);
My component already has a key passed to it. Where should I apply the key?
I don't think you want the ReactCSSTransitionGroup inside the .map function. It should be outside and ReactCSSTransitionGroup will add it's magic to each of it's children (your Note component).
It works by adding additional lifecycle methods to 'each' of it's children as they are added/removed from the DOM. So there is no need to wrap each of the Note components with ReactCSSTransitionGroup, it should simply have all the Notes as it's children.
The key warning is because ReactCSSTransitionGroup will wrap it's children in a span. When in the .map loop, react will see something like the following:
<span> <Note key={note.id} /> </span>
<span> <Note key={note.id} /> </span>
<span> <Note key={note.id} /> </span>
React will want each of the spans to have a unique key, the child Note key will be ignored.
Moving it outside the map will give you this:
<span>
<Note key={note.id} />
<Note key={note.id} />
<Note key={note.id} />
</span>
And React will be happy as each Note has a key.
Try the following:
return (
<div className="container">
<Navigation />
<div className="app-items-container">
<ReactCSSTransitionGroup {...transitionOptions}>
{this.state.notes.map((note) => {
return(
<Note noteContent={note.noteContent}
noteId={note.id}
key={note.id}
removeNote={this.removeNote} />
)
})
}
</ReactCSSTransitionGroup>
</div>
<Form addNote={this.addNote} />
</div>
);
most likely you should be adding a unique key on <ReactCSSTransitionGroup > as well, could you try the following please?
return (
<div className="container">
<Navigation />
<div className="app-items-container">
{
this.state.notes.map((i, note) => {
return(
<ReactCSSTransitionGroup key={i} {...transitionOptions}>
<Note noteContent={note.noteContent}
noteId={note.id}
key={note.id}
removeNote={this.removeNote} />
</ReactCSSTransitionGroup>
)
})
}
</div>
<Form addNote={this.addNote} />
</div>
);
also, what micposso said makes sense, so it would be nice if you could make sure that node.id is indeed always unique.

Resources