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>
Related
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>
I am beginner of react. I want to add and edit both operations at one button.
but it is not working. what i tried so far is the attached code along with the screenshot image.
I will able to add the records and able to view the records when i click the table row particular row record will be passing to form successfully. But I want edit and add the record of same button. i create the method save inside method I called save and edit functions
screenshot
this is the function i wrote the below
async function save(users)
import axios from 'axios';
import {useEffect, useState } from "react";
function EmployeeLoad()
{
const [name, setName] = useState("");
const [address, setAddress] = useState("");
const [mobile, setMobile] = useState("");
var currentEmployeeID = "";
const [users, setUsers] = useState([]);
useEffect(()=>
{
Load();
},[])
async function editEmployee(users)
{
setName(users.name);
setAddress(users.address);
setMobile(users.mobile);
currentEmployeeID = users.id;
console.log(users.id);
}
async function Load()
{
const result = await axios.get(
"http://127.0.0.1:8000/api/employees");
setUsers(result.data);
console.log(result.data);
}
async function save(users)
{
if(users.id == '')
{
await axios.post("http://127.0.0.1:8000/api/save",
{
name: name,
address: address,
mobile: mobile
}
);
alert("Employee Registation success");
}
else
{
alert("edit");
}
}
return (
<div>
<h1>Employee Details</h1>
<div class="container mt-4" >
<form>
<div class="form-group">
<label>employeeName</label>
<input type="text" class="form-control" id="employeeName"
value={name}
onChange={(event) =>
{
setName(event.target.value);
}}
/>
</div>
<div class="form-group">
<label>employeeAddress</label>
<input type="text" class="form-control" id="employeeAddress"
value={address}
onChange={(event) =>
{
setAddress(event.target.value);
}}
/>
</div>
<div class="form-group">
<label>Mobile</label>
<input type="text" class="form-control" id="employeeMobile"
value={mobile}
onChange={(event) =>
{
setMobile(event.target.value);
}}
/>
</div>
<button class="btn btn-primary mt-4" onClick={save}>Register</button>
</form>
</div>
<table class="table table-dark" align="center">
<thead>
<tr>
<th scope="col">Employee Id</th>
<th scope="col">Employee Name</th>
<th scope="col">Employee Address</th>
<th scope="col">Employee Mobile</th>
<th scope="col">Option</th>
</tr>
</thead>
{users.map(function fn(item)
{
return(
<tbody>
<tr>
<th scope="row">{item.id} </th>
<td>{item.name}</td>
<td>{item.address}</td>
<td>{item.mobile}</td>
<td>
<button type="button" class="btn btn-warning" onClick={() => editEmployee(item)} >Edit</button>
<button type="button" class="btn btn-dark" >Delete </button>
</td>
</tr>
</tbody>
);
})}
</table>
</div>
);
}
export default EmployeeLoad;
Inside your table use the currentEmployeeID and render a save button if you are in edit mode
{currentEmployeeID === item.id ? (
<button type="button" class="btn btn-warning" onClick={save} >Save</button> : (
<button type="button" class="btn btn-warning" onClick={() => editEmployee(item)} >Edit</button>
)}
So if this specific row is in edit mode, by pressing the button, it will save the entry, or else it will show "Edit". Dont forget to reset the currentEmployeeID when the save process completes.
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!!
I have a table with multiple inputs and want my second input on each row to change the number next to it with a formula of the first row: 5-DPS(from input). I want the number to change immediately after the DPS value changes.
Is there an easy-to-understand way for someone new to react?
This is my code:
import React, { useState, useEffect, useRef } from "react";
import "./index.css";
import Champions from "./components/Champions";
const Calculator = () => {
let DPS = React.createRef();
let TM = React.createRef();
let CCS = React.createRef();
let ME = React.createRef();
let UD = React.createRef();
const Burst = 5 - DPS;
const Sustain = 5 - TM;
const Hard = 5 - CCS;
const Reposition = 5 - ME;
const Offensive = 5 - UD;
//const [DPS, setDPS] = useState("");
return (
<table border={1} className="inlineTable" id="table2">
<tbody>
<tr>
<td />
<td>Pirmenybė</td>
<td>ŽPS</td>
<td>Staigus šaudymas</td>
</tr>
<tr>
<td>Žala</td>
<td>
<input type="number" id="DP" />
</td>
<td>
<input
type="number"
name="DPS"
id="DPS"
ref={DPS}
// onChange={(e) => setDPS(e.target.value)}
/>
</td>
<td>{Burst}</td>
</tr>
<tr>
<td />
<td>Pirmenybė</td>
<td>Sušvelninimas</td>
<td>Išlaikymas</td>
</tr>
<tr>
<td>Tvirtumas</td>
<td>
<input type="number" id="tP" />
</td>
<td>
{" "}
<input
type="number"
name="TM"
id="TM"
ref={TM}
//onChange={QuickChange.bind(this)}
/>
</td>
<td>Sustain</td>
</tr>
<tr>
<td />
<td>Pirmenybė</td>
<td>Minkštas</td>
<td>kietas</td>
</tr>
<tr>
<td>Minios valdymas</td>
<td>
<input type="number" id="CCP" />
</td>
<td>
<input
type="number"
name="CCS"
id="CCS"
ref={CCS}
// onChange={QuickChange.bind(this)}
/>
</td>
<td>Hard</td>
</tr>
<tr>
<td />
<td>Pirmenybė</td>
<td>Užvedimas</td>
<td>Perdėlioti</td>
</tr>
<tr>
<td>Mobilumas</td>
<td>
<input type="number" id="MP" />
</td>
<td>
<input
type="number"
name="ME"
id="ME"
ref={ME}
// onChange={QuickChange.bind(this)}
/>
</td>
<td>Reposition</td>
</tr>
<tr>
<td />
<td>Pirmenybė</td>
<td>Gynybinis</td>
<td>Agresyvus</td>
</tr>
<tr>
<td>Naudingumas</td>
<td>
<input type="number" id="UP" />
</td>
<td>
{" "}
<input
type="number"
name="UD"
id="UD"
ref={UD}
//onChange={QuickChange.bind(this)}
/>
</td>
<td>Offensive</td>
</tr>
</tbody>
</table>
);
};
export default Calculator;
You can show the value for the input with value of the state. When this value changes, it will be updated with the setDPS function.
const [DPS, setDPS] = useState(0);
<input
type="number"
name="DPS"
value={DPS}
onChange={(e) => setDPS(e.target.value)}
/>
If you want to depend this value and set other values, you can use a useEffect. When the value of DPS changes (inside the dependency array), the effect will run and update the value for the burst.
const [burst, setBurst] = useState();
useEffect(() => {
setBurst(5 - DPS)
}, [DPS])
Or you can set all values when DPS changes directly in the onChange
<input
type="number"
name="DPS"
value={DPS}
onChange={(e) => {
setDPS(e.target.value);
setBurst(5 - e.target.value);
}}
/>
I have a component, called Bucket, each bucket can have multiple challenges, it looks like this,
The code I have is like this, (much-simplified version)
class CLL_Bucket extends Component {
constructor(props) {
super(props);
this.state = {};
this.state = {
…
bucketChallengesIdx: 0, // to track the index of challegnes
bucketChallenges: this.props.bucket.bucketChallenges || [],
…
};
…
this.onBucketChallengeAdd = this.onBucketChallengeAdd.bind(this);
this.onBucketChallengeIDChanged = this.onBucketChallengeIDChanged.bind(this);
this.onBucketChallengeWeightChanged = this.onBucketChallengeWeightChanged.bind(this);
}
render() {
const bucketIdx = this.props.idx;
return (
<div style={styles.container}>
<div key={bucketIdx} className="row" style={styles.bucketStyle}>
<div className="col-md-2">
…
</div>
<div key={bucketIdx} className="col-md-4">
<div>
<label>
<span className="text-center">Challenges<span>
</label>
<button type="button" className="btn btn-success btn-sm" onClick={() => this.onBucketChallengeAdd()}>Add Challenge</button>
</div>
<table className="table table-bordered table-striped show">
<thead>
<tr>
<th>Challenge ID</th>
<th>Weight</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.bucketChallenges.map(this.renderBucketChallenges.bind(this))}
</tbody>
</table>
</div>
…
</div>
</div>
);
}
renderBucketChallenges(bucketIdx, idx){
return (
<tr key={idx}>
<td className="col-xs-3 input-group-sm">
<Select
options={challengeIDOptions}
defaultValue={challengeIDOptions[0]}
onChange={this.onBucketChallengeIDChanged.bind(this, idx)}
value={this.state.bucketChallengesID}
isSearchable={true}
/>
</td>
<td className="col-xs-1 input-group-sm">
<input type="text" className="form-control" value={this.state.bucketChallengesWeight}
onChange={(e) => this.onBucketChallengeWeightChanged(idx, e)} disabled={this.props.readOnly}>
</input>
</td>
<td className="col-xs-1 input-group-sm">
…
</td>
<td className="col-xs-1 input-group-sm">
<input className="btn btn-danger btn-sm" id="deleteButton" type="button" value="Delete" onClick={() => this.onDeleteChallenge.bind(this, bucketIdx, idx)} />
</td>
</tr>
);
}
onBucketChallengeAdd(){
var newChallengeIndex = this.state.bucketChallengesIdx + 1;
console.log("onBucketChallengeAdd(): " + newChallengeIndex);
this.setState({bucketChallengesIdx: newChallengeIndex});
this.props.onAddChallenge(this.props.idx, newChallengeIndex);
}
The problem I’m having is, when I click the “Add Challenge” button, I can see from the React developer tool that a new challenge is being added, even though the UI is not updated. When I go to a different tab of my app and come back, the UI is added (a new row for the added challenge is there). Why? Any suggestion on how to fix this? Thanks!
The bigger question is, am I on the right track to make this happen? or i should extract challenge portion to a different component?