How to check an item and disable another checkbox in react? - reactjs

I have a list of items from API. I also have two checkboxes to approve or decline an item. I want to be able to check the approve box and disable the decline box for an item.
function AllReferral() {
const [buttonStatus1, setButtonStatus1] = useState(false)
const [buttonStatus2, setButtonStatus2] = useState(false)
//function
const deactivateButton2 = () => setButtonStatus1(!buttonStatus1)
const deactivateButton1 = () => setButtonStatus2(!buttonStatus2)
return (
<section>
<div>
{user?.services?.length > 0 && (
<div>
<table>
<thead>
<tr>
<th >Approve</th>
<th >Decline</th>
<th >Service Name</th>
</tr>
</thead>
{user?.services?.map((item, index) => (
<tbody key={index}>
<tr>
<td>
<input
name={item?.name}
onClick={deactivateButton2}
type="checkbox"
value={checked}
onChange={(e) => setChecked(e.target.value)}
/>
</td>
<td>
<input
name={item?.name}
onClick={deactivateButton1}
type="checkbox"
value={checked2}
onChange={(e) => setChecked2(e.target.value)}
/>
</td>
<td>{item?.label}</td>
</tr>
</tbody>
))}
</table>
</div>
)}
</div>
</section>
);
}
Above is one of many trials I've done but I still don't get the desired action I need. I would appreciate some help

The easiest way to do this is to use a radio button. The default behavior of radio buttons is that if you select one radio button the others are automatically deselected.
If you want to have it as a checkbox, you can use a controlled input. Below is an example implementation that uses a shared state for the inputs.
function App () {
const [status, setStatus] = React.useState(false)
const handleChange = e => setStatus(prevState => !prevState)
return (
<div>
<label>
<input
type="checkbox"
checked={status}
onChange={handleChange}
/>
Accept
</label>
<label>
<input
type="checkbox"
checked={!status}
onChange={handleChange}
/>
Decline
</label>
</div>
)
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>

Related

How to check one item in a list of checkboxes in react?

I have a list of items from API with 2 checkboxes for each item. one checkbox for approve and the other for decline. But I encountered 2 problems, all the checkboxes are checked using the checked attribute.
function AllReferral() {
const [status, setStatus] = React.useState(false)
const handleChange = (item, checked) => {
setStatus((prevState) => !prevState);
checked
? setChecked((prev) => [
...prev,
{
serviceName: item?.label,
status: status,
},
])
: setChecked((prev) => [...prev, item].filter((c) => c !== item));
};
return (
<section>
<div>
{user?.services?.length > 0 && (
<div>
<table>
<thead>
<tr>
<th >Approve</th>
<th >Decline</th>
<th >Service Name</th>
</tr>
</thead>
{user?.services?.map((item, index) => (
<tbody key={index}>
<tr>
<td>
<input
name={item?.name}
type="checkbox"
checked={status}
onChange={(e) => handleChange(item, e.target.checked)}
/>
</td>
<td>
<input
name={item?.name}
type="checkbox"
checked={!status}
onChange={(e) => handleChange(item, e.target.checked)}
/>
</td>
<td>{item?.label}</td>
</tr>
</tbody>
))}
</table>
</div>
)}
</div>
</section>
);
}
from above implementation, if I have 4 items, all 4 is checked by default. I want each item in the list to be checked separately either approve or decline. Secondly I want the setChecked to return an array of both approved and declined item differentiated by status true or false.

Search bar does not retrieve data from mongodb collection

I am trying to use the data store in mongodb collection and render it in the front end. It renders the text box, labels and search button, even though it does not load any of the data. My collection name is users and my database CRDU works perfectly fine.
Please help me with this, below is my front end search.js
function Search(){
const [resultUsers, setResultUsers] = useState([]);
const [usersTable, setUsersTable] = useState([]);
const [searchP, setSearchP] = useState("");
const requestGet=async()=>{
await axios.get("mongodb://localhost:27017/projectDB/users/")
.then(response=>{
setResultUsers(response.data);
setUsersTable(response.data);
}).catch(error=>{
console.log(error);
})
}
const handleChange=e=>{
setSearchP(e.target.value);
filter(e.target.value);
}
const filter=(searchTerm)=>{
var searchResults=usersTable.filter((element)=>{
if(element.username.toString().toLowerCase().includes(searchTerm.toLowerCase())
|| element.firstName.toString().toLowerCase().includes(searchTerm.toLowerCase())
|| element.lastName.toString().toLowerCase().includes(searchTerm.toLowerCase())
){
return element;
}
});
setResultUsers(searchResults);
}
useEffect(()=>{
requestGet();
},[])
return (
<div className="Search">
{/* <Container> */}
<div className="containerInput">
<input
className="form-control search-input"
value={searchP}
placeholder="Enter username, first name or last name of the user to begin search"
onChange={handleChange} />
<button className="btn btn-success">Search for users
</button>
<br/>
</div>
{/* </Container> */}
<div className='tabled'>
<div className="table-responsive">
{/* <Container> */}
<table className="table table-sm table-bordered;">
<thead>
<tr>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
{resultUsers &&
resultUsers.map((resultUsers)=>(
<tr key={resultUsers.id}>
<td>{resultUsers.username}</td>
<td>{resultUsers.firstName}</td>
<td>{resultUsers.lastName}</td>
</tr>
))}
</tbody>
</table>
{/* </Container> */}
</div>
</div>
</div>
)
}
export default Search
Thanks in advance!!

Autocomplete feature shows [Object object]

i am trying to implement auto complete feature in react JS.
it shows the autocomplete box, but shows [Object Object] for some reason, I have no idea why. I want it to show the email in the search box so as to implement autocomplete feature.
I would like to share my source code
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './Home.css'
const SearchRepo = () => {
const [users, setUsers] = useState([]);
const [text, setText] = useState('');
const [suggestions, setSuggestions] = useState([]);
const onChangeHandler = (text) =>{
//setSeachUser(e.target.value);
let matches = []
if(text.length > 0){
matches = users.filter(user =>{
const regex = new RegExp(`${text}`,"gi");
return user.email.match(regex);
})
}
setSuggestions(matches);
setText(text);
}
useEffect(()=>{
const loadUsers = async()=>{
const response = await axios.get('https://reqres.in/api/users');
setUsers(response.data.data);
}
loadUsers();
},[])
return (
<div align="center">
<table border="0" width="100%" height="212px">
<tr>
<td bgcolor="#C0C0C0" height="55px"> <b>
<font face="Berlin Sans FB" color="#333333">Github Repo Search</font></b></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<div align="center">
<table border="0" width="100%" className="SearchTable">
<div align="center">
<input type="text" placeholder=" Enter github repo ID / username" name="T1" size="88" value={text} onChange={e =>onChangeHandler(e.target.value)} className="inputArea" />
{suggestions && suggestions.map((suggestion,i)=>{
<div key={i}>{suggestion.email}</div>
})}
</div>
</table>
</div>
<div align="center">
<table border="0" width="100%" className="reposresultsTable">
<div align="left">
<tr>
<td bgcolor="#FFFFFF"> <b>
<font face="Verdana" size="2" className="labeltxt"><h3> Repos</h3></font></b>
</td>
</tr>
</div>
<div align="left">
<tr>
<td height="23"> <b>
<font face="Verdana" size="2">
<a href="https://test-restapi2.herokuapp.com/employees/">
mmmmmmmm</a></font></b></td>
</tr>
</div>
</table>
</div>
</td>
</tr>
</table>
</div>
);
}
export default SearchRepo;
why would it be showing that Object rather than the email? Please is there something i am not getting rightly?
Thanks guys, the issue was with a Curly brace. I have been able to resolve it. Thanks everyone.
Changing from this :
<div align="center">
<input type="text" placeholder=" Enter github repo ID / username" name="T1" size="88" value={text} onChange={e =>onChangeHandler(e.target.value)} className="inputArea" />
{suggestions && suggestions.map((suggestion,i)=>{
<div key={i}>{suggestion.email}</div>
})}
</div>
to this
<div align="center">
<input type="text" placeholder=" Enter github repo ID / username" name="T1" size="88" value={text} onChange={e =>onChangeHandler(e.target.value)} className="inputArea" />
{suggestions && suggestions.map((suggestion,i)=>
<div key={i}>{suggestion.email}</div>
)}
</div>

edit and update table cell dynamically in react

I am new to react. I want to achieve the below functionality in react for a grading table of students. How can I do that?
Please refer to the images.
Change the table cell into an input box
Editable cells in the table
Here is the snippet I have tried till now
Improved your code. you can change as per your requirement. Live demo
const Grades = () => {
const [grade, setGrade] = useState("");
const [data, setData] = useState([]);
const [showEdit, setShoEdit] = useState(0);
var count = 0;
const handleChange = (event) => {
setGrade(event.target.value);
};
const addGrade = () => {
setData([...data, { Grade: grade, id: Math.floor(Math.random()*100) }]);
setGrade("");
};
const editGrade = (row) => {
console.log(row)
setShoEdit(row.id);
setGrade(row.id);
}
const saveGrade = (row) => {
let update = data.map(list =>
list.id === row.id ? ({...list, Grade: grade}) : list
);
setData([...update]);
}
return (
<div className="container-xl">
<div className="form-group row">
<div className="col-md-1">
<label className="col-form-label ">Grade</label>
</div>
<div className="col-md-4">
<input
type="text"
value={grade}
className="form-control"
name="Grade"
onChange={handleChange}
/>
</div>
{!showEdit && <div className="form-group col-md-6">
<button
type="button"
className="btn btn-outline-primary"
onClick={addGrade}
>
Add Grade
</button>
</div>}
</div>
<div className="form-group row">
<table className="table">
<thead className="thead-dark">
<tr>
<th>#</th>
<th>Grades</th>
<th>Grade Id</th>
<th>Operations</th>
</tr>
</thead>
<tbody>
{data.map((row,i) => (
<tr key={row.id}>
<td>{++count}</td>
<td>{row.Grade}</td>
<td>{row.id}</td>
<td>
{!(row.id === showEdit) ? <button
onClick={()=> editGrade(row)}
key={row.id}
className="btn btn-outline-primary"
type="button"
>
Edit
</button>:
<button
type="button"
className="btn btn-outline-primary"
onClick={()=>saveGrade(row)}
>
Save
</button>}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
export default Grades;

how to refresh just table information after clicking a button in ReactJS

I'm starting with ReactJS now. I have a table (isn't a React Component) and I need to refresh its information after clicking a button. These informations come from an array. I already exclude the informations from array, but i couldn't find a way to refresh the front end.
Here's the code:
function remove(e) {
var array = impacts;
var index = e.target.value;
array.splice(index, 1);
setImpacts(array);
//??????
}
return (
<div>
<form onSubmit={handleSubmit}>
<select id="base">
{bases.map(base => (
<option key={base._id}>{base.module}</option>
))}
</select>
<select id="impact">
<option>CPU</option>
<option>Memória</option>
<option>Filesystem</option>
<option>Tablespace</option>
</select>
<input type="number" id="qtdImpact" placeholder="Impacto" min="0" max="100" required />
<div id="label">CORES</div>
<input type="text" id="tbsfs" placeholder="Tablespace/Filesystem" />
<button type="submit" value="adicionar">ADICIONAR</button>
</form>
<button type="button" value="gerar" onClick={generateGraph}>GERAR GRAFICOS</button>
<div id="div-tabela">
<table id="tabela">
<thead>
<tr>
<td>NOME DA BASE</td>
<td>MODULO</td>
<td>REMOVER</td>
</tr>
</thead>
<tbody>
{
impacts.map((each, index) => (
<tr key={index}>
<td>{each.module}</td>
<td>{each.type}</td>
<td><button type="button" value={index} onClick={remove}>REMOVER</button></td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
);
The remove function is where I'm removing the informations from array, and might be here that I need to refresh the front end.
Someone has any idea of how to do this?
Thanks
try this
var index = e.target.value;
impacts.splice(index, 1);
setImpacts([...impacts]);

Resources