I created a simple app to search video using youtube-api, but when I use npm start it was not give me any errors but give me the warning Warning: Unknown proponItemSearchedon <searchItem> tag. Remove this prop from the element.
in searchItem (created by listItem)
in div (created by listItem)
in listItem
Here is my code:
var React = require('react');
var Item = require('./item.jsx');
var searchItem = React.createClass({
getInitialState : function() {
return {
'queryString' : ''
};
},
handleSearchClicked : function() {
this.props.onItemSearched(this.state);
this.setState({
'queryString' : ''
});
},
handleChangedNameItem : function(e) {
e.preventDefault();
this.setState({
'queryString' : e.target.value
});
},
render : function () {
return (
<div>
<label>
<input id="query" type="text" onChange={this.handleChangedNameItem} value={this.state.queryString} placeholder="Search videos..." />
<button id="search-button" onClick={this.handleSearchClicked}>Search</button>
</label>
</div>
);
}
});
And this is listItem what i show my results
var listItem = React.createClass({
getInitialState : function() {
return {
'results' : []
};
},
handleQuerySearch : function(query) {
var req = gapi.client.youtube.search.list({
'part': 'snippet',
'type': 'video',
'q' : encodeURIComponent(query).replace(/%20/g, "+"),
'order' : 'viewCount',
});
//execute request
req.execute((res) => {
var results = res.result;
this.setState({
'results' : results.items
});
});
},
render : function() {
var listItem = this.state.results.map( item => {
return(
<Item title={item.snippet.title} videoid={item.id.videoId} />
);
});
return (
<div>
<searchItem onItemSearched={this.handleQuerySearch} />
<div className="list-item">
{listItem}
</div>
</div>
);
}
});
module.exports = listItem;
React wants all components to be written in class format. Meaning the names need to be capitalized.
searchItem needs to be SearchItem
You can also define the props that will be received on search item
var SearchItem = React.createClass({
propTypes: {
onItemSearched: React.PropTypes.func
},
....
});
Related
I am trying to get the nested array from a input value of a checkbox.
How do I handle a nested array?
These are the values:
const othersOptions = [
{procedure:'ORAL PROPHYLAXIS',price: 1000},
{procedure:'TOOTH RESTORATION',price:1200},
{procedure:'TOOTH EXTRACTION',price:800}
];
This is how I get the values from checkbox. I am guessing that value={[item]} is procedure:'ORAL PROPHYLAXIS',price: 1000 if the ORAL PROPHYLAXIS checkbox is checked
<Form>
{othersOptions.map((item, index) => (
<div key={index} className="mb-3">
<Form.Check
value={[item]}
id={[item.procedure]}
type="checkbox"
label={`${item.procedure}`}
onClick={handleChangeCheckbox('Others')}
required
/>
</div>
))}
</Form>
When I console.log the value it shows that the value is [Object object] this is the value.
const handleChangeCheckbox = input => event => {
var value = event.target.value;
console.log(value, "this is the value")
var isChecked = event.target.checked;
setChecked(current =>
current.map(obj => {
if (obj.option === input) {
if(isChecked){
return {...obj, chosen: [{...obj.chosen, value}] };
}else{
var newArr = obj.chosen;
var index = newArr.indexOf(event.target.value);
newArr.splice(index, 1);
return {...obj, chosen: newArr};
}
}
return obj;
}),
);
console.log(checked);
}
and this is how I save the nested array:
const [checked, setChecked] = useState([
{ option: 'Others',
chosen: [],
]);
The reason why I need the procedure and price is so that I can save the values to MongoDB and get the values to another page which is a Create Receipt page. I want the following procedures price to automatically display in the Create Receipt page.Thank you for the help!
If anyone is wondering how I fixed it.
I stringfy the input values and parsed the e.target.values
import "./styles.css";
import { Form } from "react-bootstrap";
import { useState } from "react";
import React from "react";
const othersOptions = [
{ procedure: "ORAL PROPHYLAXIS", price: 1000 },
{ procedure: "TOOTH RESTORATION", price: 1200 },
{ procedure: "TOOTH EXTRACTION", price: 800 },
{ procedure: "DEEP SCALING", price: 10200 },
{ procedure: "PTS AND FISSURES SEALANT", price: 700 },
{ procedure: "FLOURIDE TREATMENT", price: 5500 },
{ procedure: "INTERMEDIATE RESTORATION", price: 7000 },
{ procedure: "ORTHODONTICS", price: 48000 }
];
export default function App() {
const [checked, setChecked] = useState([{ option: "Others", chosen: [] }]);
console.log(checked);
const handleChangeCheckbox = (input) => (event) => {
var value = JSON.parse(event.target.value);
var isChecked = event.target.checked;
console.log("value is:", value[0].procedure);
var tempArr = { procedure: value[0].procedure, price: value[0].price };
setChecked((current) =>
current.map((obj) => {
if (obj.option === input) {
if (isChecked) {
return { ...obj, chosen: [...obj.chosen, tempArr] };
} else {
var newArr = obj.chosen;
var index = newArr.indexOf(event.target.value);
newArr.splice(index, 1); // 2nd parameter means remove one item only
return { ...obj, chosen: newArr };
}
}
return obj;
})
);
};
return (
<Form>
{othersOptions.map((item, index) => (
<div key={index} className="mb-3">
<Form.Check
value={JSON.stringify([item])}
id={[item]}
type="checkbox"
label={`${item.procedure}`}
onClick={handleChangeCheckbox("Others")}
required
/>
</div>
))}
</Form>
);
}
RUN THE CODE HERE
After a search, I am sending the result to frontend in the form of array. But I am not being able to get that array in frontend using fetch. Through postman I am able to get the result from the backend but I am not able to get it in the frontend. In another file, I have set axios.post as well and exported from there and imported in frotend.
I am beginner so I might have written a bad code, any help will mean a lot.
In frontend :
class Hostel extends Component{
constructor (){
super();
this.state = {
country : '',
city : '',
category : '',
errors : {}
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}
}
onChangeAddOptions = e => {
this.setState({ [e.target.id]: e.target.value });
};
addOption = e => {
e.preventDefault();
const newOption = {
country : this.state.country,
city : this.state.city,
category:this.state.category,
}
this.props.saveOptions(newOption,this.props.history);
};
getHostels = async ()=> {
console.log("getHostel function is called");
const response = await fetch('http://localhost:5000/api/users/hostel',{
method : "POST",
// headers:{
// "Content-Type" : "application/json"
// },
})
.then((response)=> {response.json()})
.then((data)=>{
console.log("inside data");
console.log(data);
})
.catch(e=>{
console.error(e.error);
})
console.log("From outside of data");
console.log(response);
}
componentDidMount(){
this.getHostels();
}
render (){
const {errors,country,city,category} = this.state;
return(
<section className="Hosteldashboard">
<div className="left_container">
<h2>Yo che left section</h2>
<div>
<form noValidate onSubmit={this.addOption}>
<div class="form-row">
<label htmlFor="country">Country</label> <br />
<input
type="text"
className="input-control"
placeholder="Country name"
id="country"
value={country}
onChange={this.onChangeAddOptions}
error={errors.country}
className={classnames('', {
invalid: errors.country
})}
/>{' '}
<br />
<span className="text-danger">{errors.country}</span>
</div>
<div class="form-row">
<label htmlFor="city">City</label> <br />
<input
type="text"
className="input-control"
placeholder="City name"
id="city"
value={city}
onChange={this.onChangeAddOptions}
error={errors.city}
className={classnames('', {
invalid: errors.city
})}
/>{' '}
<br />
<span className="text-danger">{errors.city}</span>
</div>
<div class="form-row">
<label htmlFor="category">Category</label> <br />
<input
type="text"
className="input-control"
placeholder="Boys or Girls"
id="category"
value={category}
onChange={this.onChangeAddOptions}
error={errors.category}
className={classnames('', {
invalid: errors.category
})}
/>{' '}
<br />
<span className="text-danger">{errors.category}</span>
</div>
<div>
<button type="submit" className = "searchHostel" onClick={this.getHostels}>
Search
</button>
</div>
</form>
</div>
</div>
In backend :
router.post('/hostel',async (req,res)=>{
try{
console.log(req.body);
const {
errors,
isValid
} = validateSearchHostelInput(req.body);
//Check Validation
// if (!isValid){
// return res.status(400).json(errors);
// }
const page = parseInt(req.query.page) - 1 || 0;
const limit = parseInt(req.query.limit) || 5;
const search = req.query.search || "";
let sort = req.query.sort || "price";
let category = req.query.category || "All";
const categoryOptions = [
req.body.country,
req.body.city,
req.body.category
]
category === "All"
? (category = [...categoryOptions])
: (category = req.query.category.split(","));
req.query.sort ? (sort = req.query.sort.split(",")) : (sort = [sort]);
let sortBy = {};
if(sort[1]) {
sortBy[sort[0]] = sort[1];
} else {
sortBy[sort[0]] = "asc";
}
const hostel = await Hostel.find({title: {$regex: search, $options: "i"}})
.where("category")
.in([...category])
.sort(sortBy)
.skip(page * limit)
.limit(limit);
// const total = await Hostel.countDocuments({
// category: {$in: [...category]},
// title: { $regex: search, $options: "i"},
// });
// const response = {
// error: false,
// total,
// page: page + 1,
// limit,
// categories: categoryOptions,
// hostel
//}
console.log("From Hostel : " + hostel);
res.status(200).json({hostel:hostel});
}catch(err){
console.log(err);
res.status(500).json({error:true,message:"Internal Server Error"});
}
});
module.exports = router;
My Goal for this one is to Add ObjectId inside the array
In my backend Im declare schema on this code:
tchStudents: [{
type: Schema.Types.ObjectId,
ref: "Student"
}]
THen Im do adding an ObjectId to insert to the array of ObjectID:
My BackEnd is very fine
router.put('/assignAddStudents/:tchID', async (req,res) => {
try {
const searchTch = await Teacher.findOne({ tchID: req.params.tchID })
if(!searchTch){
return res.status(404).send({
success: false,
error: 'Teacher ID not found'
});
} else {
let query = { tchID: req.params.tchID }
let assignedStudentObjID = {$push:{tchStudents: req.body.tchStudents }}
Teacher.updateOne(query, assignedStudentObjID ,() => {
try{
return res.status(200).send({
success: true,
msg: 'Student ID has been assigned'
});
} catch(err) {
console.log(err);
return res.status(404).send({
success: false,
error: 'Teacher ID not found'
})
}
})
}
} catch (err) {
console.log(err)
}
})
But my Front End Not working
err: BAD REQUEST(400) Unexpected token " in JSON at position 0
import React, {useState} from 'react'
import axios from 'axios'
import { URL } from '../../utils/utils'
import { Modal, Button } from 'react-materialize';
import ListTchStudents from '../lists/ListTchStudents';
const trigger =
<Button
style={{marginLeft:'2rem'}}
tooltip="Add More..."
tooltipOptions={{
position: 'top'
}}
className="btn-small red darken-4">
<i className="material-icons center ">add_box</i>
</Button>;
const MdlAddStudents =({teacher}) => {
const [data, setData] = useState('');
const { tchStudents} = data;
const {
tchID,
} = teacher; // IF WE RENDER THIS IT TURNS INTO OBJECT
const assignedStudent = () => {
// BUT WE SENT IT TO THE DATABASE CONVERT TO JSON.STRINGIFY to make ObjectId
const requestOpt = {
method: 'PUT',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify(data)
}
axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data,requestOpt)
.then(res => {
setData(res.data.data)
})
}
return (
<Modal header="Add Students" trigger={trigger}>
Please ADD and REMOVE Student ID No. for {tchID}
<div>
<ul
style={{marginBottom:'2rem'}}
className="collection">
{
Object.values(teacher.tchStudents).map(tchStudent => {
return(
<ListTchStudents
tchStudent={tchStudent}
/>
);
})
}
</ul>
<div className="row">
<div className="col s6 offset-s3"></div>
<div className="input-field">
<label
htmlFor=""
className="active black-text"
style={{fontSize:'1.3rem'}}>
Add Students here:
</label>
<input
type="text"
name="tchStudents"
value={(tchStudents)}
className="validate"
onChange={(e) => setData(e.target.value)}
/>
</div>
</div>
</div>
{/* BUT WE SENT IT TO THE DATABASE CONVERT TO JSON.STRINGIFY to send ObjectId to the database
*/}
<div className="row">
<div className="col s2 offset-s3" ></div>
<Button
onClick={assignedStudent}
tooltip="Add Students"
tooltipOptions={{
position: 'right'
}}
className="btn green darken-3">
<i className="material-icons ">add_circle</i>
</Button>
</div>
<p>There are {Object.values(teacher.tchStudents).length} student/s
assigned</p>
</Modal>
)
}
// MdlAddStudents.propTypes = {
// assignedStudents: PropTypes.func.isRequired,
// }
export default MdlAddStudents;
// export default connect(null, (assignedStudents))(MdlAddStudents);
Thank you for helping out
The problem stems from you attempting to wrap your tchStudents state property in an object named data.
My advice is to keep it very simple
// it's just a string
const [tchStudents, setTchStudents] = useState("")
const assignedStudent = () => {
// create your request payload
const data = { tchStudents }
// no config object required
axios.put(`${URL}teachers/assignAddStudents/${tchID}`, data)
.then(res => {
// not sure what you want to do here exactly but
// `res.data` should look like
// { success: true, msg: 'Student ID has been assigned' }
setTchStudents("") // clear the input ¯\_(ツ)_/¯
})
}
The only other change is to use the new setter name in your <input>...
<input
type="text"
name="tchStudents"
value={tchStudents}
className="validate"
onChange={(e) => setTchStudents(e.target.value)}
/>
I am using ExpressJS with EJS template view engine. I am trying to show an HTML file on the angular component, but the form tag and its child input tag do not work on the angular side. They show only label data.
On NodeJS
agreementController.js
exports.getAgreementHtml = async (request, response, next) => {
const params = request.query
let reqPath = path.join(__dirname, '../agreements');
var agreementObj = {
user: { email: "example#gmail.com" }
}
// render domestic rent html
ejs.renderFile(reqPath + '/domestic_rent.ejs', agreementObj, {}, function (err, str) {
if (err !== null) {
responseObj.status = errorCodes.DATA_NOT_FOUND
responseObj.message = language.getMessage('NO_RECORD_FOUND')
response.send(responseObj)
return
}
responseObj.status = errorCodes.OK
responseObj.data = str
response.send(responseObj);
return;
});
}
domestic_rent.js
<form>
<div class="form-group">
<p><%= user.email %></p>
<div class="col-sm-offset-2 col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="test" required name="test">
</div>
</div>
</form>
On Angular 8 Side
agreement-show.component.ts
getAgreementData() {
const params = {
id: this.agreementId
};
this.agreementService.getAgreementHtml(params).subscribe(
(result) => {
console.log('result agreement data::: ', result);
if (result.status !== 200) {
this.commonService.change.emit({ status: 'error', message: 'unknown error' });
return;
}
this.someHtml = result.data;
return;
}, (error) => {
console.log('error', error)
this.commonService.change.emit({ status: 'error', message: error.message });
}
);
}
agreement-show.component.html
<div [innerHTML]="someHtml"></div>
Output Attachment
By using ElementRef function we can add html runtime.
Please use following step:
#ViewChild('showitems') showitems: ElementRef;
const elemt: HTMLElement = this.showitems.nativeElement;
this.someHtml = result.data;
elemt.innerHTML = this.someHtml;
How do I access in React, a method of one component in other components, that are not in a direct parent-child relation? For example:
var QuestionsBox = React.createClass({
**editQuestion**: function(questionId){
// do something
// this.refs.mainForm.loadQuestionFromServer.bind(this, questionId);
},
getInitialState: function() {
return {data: []};
},
render: function() {
return (
<div className="questionsBox">
<h4>Questions</h4>
<QuestionsList data={this.state.data}/>
</div>
);
}
});
var QuestionsList = React.createClass({
render: function() {
var reactObject = this;
var questionsList = this.props.data.map(function (question) {
return (
<Question id={question.id}>
{question.question_name}
</Question>
);
});
return (
<div>
{questionsList}
</div>
);
}
});
var Question = React.createClass({
render: function() {
return(
<div className="question">
{this.props.children}
<a onClick={**access here editQuestion method of QuestionsBox component, with parameters**}>edit</a>
</div>
);
}
});
or other similar structures, that do not have a direct parent-child relation..
You need to pass it down as a prop
var QuestionsBox = React.createClass({
**editQuestion**: function(questionId){
// do something
// this.refs.mainForm.loadQuestionFromServer.bind(this, questionId);
},
getInitialState: function() {
return {data: []};
},
render: function() {
return (
<div className="questionsBox">
<h4>Questions</h4>
<QuestionsList
data={this.state.data}
editQuestion={this.editQuestion}
/>
</div>
);
}
});
var QuestionsList = React.createClass({
render: function() {
var reactObject = this;
var questionsList = this.props.data.map(function (question) {
return (
<Question>
id={question.id}
editQuestion={this.props.editQuestion}
{question.question_name}
</Question>
);
});
return (
<div>
{questionsList}
</div>
);
}
});
var Question = React.createClass({
render: function() {
return(
<div className="question">
{this.props.children}
<a id={this.props.id} onClick={this.editQuestion}>edit</a>
</div>
);
},
editQuestion: function(e) {
this.props.editQuestion(e.target.id);
}
});
Create a separate storage class. Embed the instance of that class in each place that has access to editing the data it contains. You see this in Flux, Facebook's architecture library. Instead of passing down handlers, have the events be emitted from the Storage class, and have each component subscribe to that instance of the storage class.
It's hard to describe, but that link has a video which will make it very clear. This way, any time data changes the store will trigger events which will trigger re-renders of your react views.