Reactjs filter where result is zero - javascript

I want to have text on the page change when no items from a mapped array are showing.
I am showing a list of questions, but if a question is "answered" (a boolean of answered: true), it is not mapped.
I'm trying to figure out the best way to determine if every item in the array has answered: true, and then change text on the page accordingly. Is it possible to use filter for this when I need a function that checks for no results coming back?
The page shows a list to the left, and the text "please click on a question" to the right. When a question is selected, it replaces "please click on a question" with information about the selected question. But when there are no questions, I want "please click on a question" to show something like "There are currently no questions to answer".
this.state = {
questions: [],
currentQuestion: null,
currentIndex: -1,
searchQuestion: "",
wanttodelete: false
};
{questions &&
questions.map((question, index) => (
<div key={index}>
{!question.answered &&
<li
className={
"list-group-item " +
(index === currentIndex ? "active" : "")
}
onClick={() => this.setActiveQuestion(question, index)}
key={index}
>
<p>
{question.question}
</p>
</li>
}
</div>
))}
</ul>
</div>
<div className="col-lg-8 question-area">
{currentQuestion ? (
<div>
<h4>
<FormattedMessage
id="question-list.questionHeader"
defaultMessage="Question"
description="Question header"/>
</h4>
<div>
<label>
<strong>Question:</strong>
</label>{" "}
{currentQuestion.question}
</div>
<div>
<label>
<strong>Category:</strong>
</label>{" "}
{currentQuestion.categoryId}
</div>
<div>
<label>
<strong>Status:</strong>
</label>{" "}
{currentQuestion.answered ? "Answered" : "Awaiting answer"}
</div>
<Link
to={"/questions/" + currentQuestion.id}
className="badge badge-warning"
>
Answer this question
</Link>
</div>
) : (
<div>
<p>Please click on a Question...</p>
</div>
)}
</div>
</div>
</div>
</div>
);
}
}

const nothingToAnswer = questions.every(question => question.answered);

Related

How to add border to a active div?

I want to make a border when the user set a div active.
I tried to add hover, selected and active, but it did not work.
This is the part that user will select
{this.state.fields.map((fields, k) =>
<div key={k} onClick={() => this.setState({
activeFields: fields
})}>
<div className="detailsPage-details " >
{fields.map((field) =>
<p key={k}>
{field.value}: {field.key}
</p>
)}
</div>
</div>
)}
How can I do that?
Your fields should have a unique field so that you could check which field was set to active, you could use the index of the array but it is not preferred as could lead to bugs.
{this.state.fields.map((field, k) =>
<div className={this.state.activeField===field.id?"active-div":""} key={k} onClick={() => this.setState({
activeField: field.id
})}>
<div className="detailsPage-details " >
{fields.map((field) =>
<p key={k}>
{field.value}: {field.key}
</p>
)}
</div>
</div>
)}

Add popup in every item of flatlist in React

I would like to add a popup form in each item in the Flatlist, and the item is actually a card.
My problem is that every time, I clicked the button, the popup shows but, when my mouse moves out of the card, instead of showing the original one, it shows another popup whose parent is the whole page.
I know the problem should be that I need not set the variable setPopup properly. But I don't know how to fix it.
When my mouse is on the card:
enter image description here
When my mouse is out of the card, the popup will move up and its position will be based on the whole page:
enter image description here
Thank you!
This is my code.
const [buttonPopUp, setButtonPopUp] = useState(undefined);
const renderItem = (item, index) => {
return(
<Card key={index} style={{width: '20rem'}}>
<CardImg className='galleryPics' top src={galleryPic.img} alt="..."/>
<CardBody>
<PopUpEditGallery
gallery={item}
index = {index}
trigger={buttonPopUp}
setTrigger={setButtonPopUp}
>
Edit
</PopUpEditGallery>
<CardTitle className='cardTitle'>{item.title}</CardTitle>
<CardText className='cardText'>{item.description}</CardText>
<Button className="btn-round btn-icon" color="primary" size='sm' onClick={()=> setButtonPopUp(index)}>Edit</Button>
</CardBody>
</Card>
);
}
return (
<div>
<div>
<Header/>
</div>
<div className="container">
<div className="row">
<div className='col-7'>
<ul>
<FlatList
list={values.gallery}
renderItem={renderItem}/>
</ul>
</div>
</div>
</div>
</div>
)
code for popup
return (props.trigger != undefined) ? (
props.trigger == props.index &&
<div className='popup'>
<div className='popupInner'>
<form onSubmit={handleSubmit(onSubmit)}>
<FormGroup>
<Label>Title</Label>
<Input
type="text"
placeholder={prev.title}
onChange={val => props.setTitle(val.target.value, prev.idx)}
/>
</FormGroup>
<Button className="btn-round btn-icon" color="primary" size='sm'>
Submit
</Button>
<Button className="btn-round btn-icon" color="default" size='sm'>
Cancel
</Button>
</form>
</div>
</div>
): "";

Multiple readmore buttons working at the same time

Good Morning.
I'm trying to use "readmore" buttons on texts coming from the firestore
<section className="escritos">
{escritos.map(escrito => {
return (
<div>
<p>
Autor: <strong>{escrito.autor}</strong>
</p>
<p>
{" "}
Título: <strong>{escrito.titulo}</strong>
</p>
<div id="obras">
{" "}
{readmore
? parse(escrito.escrito)
: parse(escrito.escrito.substring(0, 200))}
<button id="readmore" onClick={() => setReadmore(!readmore)}>
{readmore ? "ler menos" : "ler mais"}
</button>
<Link to="#beginning">
<BsFillArrowUpCircleFill />
</Link>
</div>
<hr />
</div>
);
})}
</section>
It's working. But it works at the same time for all buttons.
I've already tried to use react-read-more, but there was an error because I have to use parse(escrito.escrito) to remove the html tags. Removing the parse, it works but with the tags showing.
It has something to do with the map I believe, but I haven't been able to solve it yet.
Here's the site and here's the repository if it helps.
Thank you in advance for your attention and your time.
Since you want the readmore state to be applied to the individual boxes you could store an array in the state and check, if the id is set, but I would go with the (in my opinion) simpler way:
Extract your block into its own component, which has its own state readmore like so:
<section className="escritos">
{escritos.map(escrito => (
<Escrito escrito={escrito} key={escrito.id} />
))}
</section>
// Escrito.jsx
const Escrito = ({escrito}) => {
const [readmore, setReadmore] = useState(false);
return (
<div>
<p>
Autor: <strong>{escrito.autor}</strong>
</p>
<p>
{" "}
Título: <strong>{escrito.titulo}</strong>
</p>
<div id="obras">
{" "}
{readmore
? parse(escrito.escrito)
: parse(escrito.escrito.substring(0, 200))}
<button id="readmore" onClick={() => setReadmore(!readmore)}>
{readmore ? "ler menos" : "ler mais"}
</button>
<Link to="#beginning">
<BsFillArrowUpCircleFill />
</Link>
</div>
<hr />
</div>
);
}
export default Escrito;
Since each component now has its own state, this should be the behavior you want.
Parent element returned from the escritos.map(escrito => {JSX}) should contain a key attribute with unique value. Read more here

ReactJs force input focus on div button click not working

I'm working on a modal in react where I have to click a button outside an input element and focus the input element and change the value. I set the input element to be disabled on default and for the edit button to remove the disabled property and then focus the element. the element is not getting visible focused neither is the disabled property being removed. It looks like it happens in a split second and then returns back to normal because whenever I check if the element is being focused on my console it displays true but It's not being visible focused.
below is my code
EDIT FUNCTION
const [editState,setEditState] = useState(null)
const editCatName = (e,id)=>{
e.stopPropagation();
setEditState({...editState,id: categories[id].id})
setActiveButton('editcatname');
let row = document.querySelectorAll('.cat-row')[id].querySelector('input');
console.log('row',row)
row.classList.remove('pointer');
row.value='Row value set'
row.hasAttribute('disabled') && row.toggleAttribute('disabled')
row.focus();
console.log(row.value)
}
const [activeButton,setActiveButton] = useState('newproduct');
const ProductCategoryModal = ()=>{
return(
<div
onClick={()=>{setCategoryModal(false)}}
className="_modal fixed " style={{zIndex:'100'}} >
<div
onClick={e=>e.stopPropagation()}
className='wytBg boxRad paddBoth sectPad relative'>
<div>
<div className="flexBtw">
<h3 className="head flexAl">Product Categories</h3>
<div className='head'> <AiOutlinePlus/> </div>
</div>
</div>
<GridStyle className='nestM' gridp='45% 55%' gap='0em'>
<Scrolldiv className='' measure='300px'>
{
categories && categories.length?
categories.map((ctg,key)=>
ctg.name !=='Others' &&
<div key={key}
onClick={(e)=>
fixCategoryDetail(ctg.id,e)
}
className={`cat-row cursor rowws flexBtw ${ key===0 && 'rows-
top'}`}>
<div>
<input
defaultValue={ctg.name}
// disabled
style={{maxWidth:'180px'}}
className={'categoryInput pointer '+ key}
onChange={e=>setEditState({
id:ctg.id,
value:e.target.value
})}
onBlur={e=>{
e.target.value=ctg.name
}}
/>
{/* {ctg.name} */}
</div>
<div className="smallflex hashEdit">
<div>
<BiEditAlt
className='cursor'
FUNCTION TO FOCUS ELEMENT IS HERE
onClick={e=>editCatName(e,key)}
/>
</div>
{
!products.find(prod=>prod.category ===ctg.id) &&
<div className='hash'> <CgClose className='cursor'/> </div>
}
</div>
</div>
):null
}
</Scrolldiv>
<Scrolldiv measure='300px' className='secondRow paddBoth'>
{
categoryDetail.length?
<div className=" search flexC">
<div>
<SearchInputBox
icon={ <CgSearch style={{width:30}} />}
padLeft={'10px'}
className='searchInput smalltxt'
inputPadding='0.5em 0.6em'
// onchange={filterByStarts}
iconPosition
summary='Type or search a product'
options=
{products.filter(prod=>
prod.category===3).map(prod=>prod.name)}
inputClassName={'searchInput smalltxt'}
pad='0'
/>
<div className="nestM flex">
<div measure='150px' >
{
categoryDetail.length?
categoryDetail.map((ctg,key)=>
ctg.category !== 3 &&
<div key={key} className=
{`doubleflex flexBtw smalltxt
itemunits ${key!==0 &&
'smallM'} `}>
<div>{ctg.name}</div>
<div>
<CgClose onClick=
{()=>removeProductFromCategory
(ctg.id,ctg.name)}
className='cursor'/>
</div>
</div>
):null
}
</div>
</div>
</div>
</div>
:null
}
</Scrolldiv>
</GridStyle>
<div className="section flexC">
<button style={{maxWidth:'70%'}}
onClick={()=>
activeButton==='newproduct'?removeProductFromCategory():
activeButton==='addcategory'?createNewCategory():
editCategoryName()}
className="submit-button category-submit">
Update
</button>
</div>
</div>
</div>
)
}

React List box how to transfer other side?

I have a dual list box but ı cant transfer the other side ? I have a two button right side and left side
when user click ex:admin and click the right button transfer the other side. How can I do that ? Anyone help ? I am trying but ı couldnt.
I am using react v 0.14 also ı dont want to use any npm[![enter image description here][1]][1]
[![List Box[2]][2]
menuClick = (activeItem) =>{
console.log('activeItem' + activeItem);
}
render() {
var role = ['admin' , 'user' , 'Deneme' , 'Denem1']
var activeRole =['SuperAdmin']
return (
<section >
<div> <h4>Active Role List</h4> </div>
<Card >
<ul>
{role.map((activeItem)=> <li value={activeItem} onClick={() => this.menuClick(activeItem)} > <a>{activeItem} </a> </li> )}
</ul>
</Card>
<div className="div2">
<button><i className="material-icons">keyboard_arrow_right</i></button>
<button> <i className="material-icons">keyboard_arrow_left</i> </button>
</div>
<div className="div3">
<div> <h4>Selected Role List</h4> </div>
<Card className="admin_create_card" id="kryesore">
<ul>
{activeRole.map((activeItem)=> <li value={activeItem} onClick={() => this.menuClick(activeItem)} > <a>{activeItem} </a> </li> )}
</ul>
</Card>
</div>
</section>
)
}```
[1]: https://i.stack.imgur.com/770vw.png
[2]: https://i.stack.imgur.com/oalmT.png

Categories

Resources