I want to setstate of PageSearchByExcel's class but I know that (this) is no longer to PageSearchByExcel.
Have you some way to set state to a totalMatchSample variable.
I bring this code from ant-design Official web.
https://ant.design/components/upload/
I'm very new to react.
Help me, please.
Or If you have another way that is better than this way please give it to me.
import ...
const props = {
name: 'file',
multiple: true,
action: API_URL + '/api/search/excelfile',
onChange(info) {
const status = info.file.status;
const data = new FormData()
data.append('file', info.file.originFileObj, info.file.name)
Axios.post(props.action, data)
.then((Response) => {
this.setState({
totalMatchSample: info.file.response.length
})
})
},
};
export default class PageSearchByExcel extends React.Component {
constructor(props) {
super(props)
this.state = {
totalSample: 0,
totalMatchSample: 0
}
}
render() {
return (
<div>
<Dragger {...props}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p>
</Dragger>
<div>
<p>
{this.state.totalMatchSample} matched samples from
{this.state.totalSample} samples
</p>
<br />
</div>
</div>
)
}
}
Since you're declaring props outside the PageSearchByExcel component the this refers to props object itself and not the component. You can define the onChange method on the component and pass it down as a prop to Dragger which then will be correctly bound to PageSearchByExcel.
import ...
const props = {
name: 'file',
multiple: true,
action: API_URL + '/api/search/excelfile',
};
export default class PageSearchByExcel extends React.Component {
constructor(props) {
super(props)
this.state = {
totalSample: 0,
totalMatchSample: 0
}
}
// Define onChange here
onChange = (info) => {
const status = info.file.status;
const data = new FormData()
data.append('file', info.file.originFileObj, info.file.name)
Axios.post(props.action, data)
.then((Response) => {
this.setState({
totalMatchSample: info.file.response.length
})
})
}
render() {
return (
<div>
<Dragger {...props} onChange={this.onChange}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p>
</Dragger>
<div>
<p>
{this.state.totalMatchSample} matched samples from
{this.state.totalSample} samples
</p>
<br />
</div>
</div>
)
}
}
Hope this helps !
#sun, based on what you posted, i will assume that you have some sort of props being passed to PageSearchByExcel component.
having said that, that props object, its an anti-pattern, you really want to pass each key in that props object to PageSearchByExcel down via the props system.
ex:
Class ParentComponent ...
...some code
render () {
..someJSX
<PageSearchByExcel name='file' multiple={true} />
}
this will basically setup your props inside PageSearchByExcel
now thats out of the way, let's talk about setState({}) and loading resources
in your PageSearchByExcel Component, you would have something like this
export default class PageSearchByExcel extends React.Component {
constructor(props) {
super(props)
this.state = {
totalSample: 0,
totalMatchSample: 0
}
}
// define your axios call inside your component class NOT OUTSIDE
loadResource = () => {
// ....yourAxiosCodeHere
}
// You then set the state at the first load of the component
componentDidMount () {
this.loadResource()
}
render() {
return (
<div>
<Dragger {...this.props}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p>
</Dragger>
<div>
<p>
{this.state.totalMatchSample} matched samples from
{this.state.totalSample} samples
</p>
<br />
</div>
</div>
)
}
}
TAKEAWAY::
1.) define your class methods inside the class itself in order the properly reference 'this'
2.) make sure you pass the props down from the parent component down to your PageSearchByExcel
3.) make sure you load your resource using the react life cycle method
This should get you going.
Related
I'm working on a CV Generator and I don't know how to properly append the school and field of study values to a new div inside React.
Using the onSubmit function I'm able to get the values after filling them out and clicking save, but I can't figure out where to go from here.
Update
What I want to do is take the values from the input and create a new div above the form that displays those values. For example, I want the School value to show
School: University of Whatever
And the same goes for Field of Study.
Field of Study: Whatever
I know how to do this in vanilla JS but taking the values and appending them to the DOM but it doesn't seem to work that way in React.
class Education extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit = (e) => {
e.preventDefault();
const schoolForm = document.getElementById("school-form").value;
const studyForm = document.getElementById("study-form").value;
};
render() {
return (
<>
<h1 className="title">Education</h1>
<div id="content">
<form>
<label for="school">School</label>
<input
id="school-form"
className="form-row"
type="text"
name="school"
/>
<label for="study">Field of Study</label>
<input
id="study-form"
className="form-row"
type="text"
name="study"
/>
<button onClick={this.onSubmit} className="save">
Save
</button>
<button className="cancel">Cancel</button>
</form>
)}
</div>
</>
);
}
}
export default Education;
You should use state in order to save the values then show it when the user submits.
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { scool: "", study: "", showOutput: false };
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit = (e) => {
e.preventDefault();
this.setState({
showOutput: true
});
};
setStudy = (value) => {
this.setState({
study: value
});
};
setSchool = (value) => {
this.setState({
school: value
});
};
render() {
return (
<>
<h1 className="title">Education</h1>
<div id="content">
{this.state.showOutput && (
<>
<div>{`school: ${this.state.school}`}</div>
<div>{`study: ${this.state.study}`}</div>
</>
)}
<form>
<label for="school">School</label>
<input
id="school-form"
className="form-row"
type="text"
name="school"
onChange={(e) => this.setSchool(e.target.value)}
/>
<label for="study">Field of Study</label>
<input
id="study-form"
className="form-row"
type="text"
name="study"
onChange={(e) => this.setStudy(e.target.value)}
/>
<button onClick={this.onSubmit} className="save">
Save
</button>
<button className="cancel">Cancel</button>
</form>
)
</div>
</>
);
}
}
export default App;
I have also added 2 functions to set state and a condition render based on showOutput.
You don't append things to the DOM in react like you do in vanilla. You want to conditionally render elements.
Make a new element to display the data, and render it only if you have the data. (Conditional rendering is done with && operator)
{this.state.schoolForm && this.state.studyform && <div>
<p>School: {this.state.schoolForm}</p>
<p>Field of Study: {this.state.studyForm}</p>
</div>}
The schoolForm and studyForm should be component state variables. If you only have them as variables in your onSubmit, the data will be lost after the function call ends. Your onSubmit function should only set the state, and then you access your state variables to use the data.
Do not use document.getElementById. You don't want to use the 'document' object with react (Almost never).
You can access the element's value directly using the event object which is automatically passed by onSubmit.
handleSubmit = (event) => {
event.preventDefault();
console.log(event.target.school.value)
console.log(event.target.study.value)
}
Codesandbox: https://codesandbox.io/s/github/adamschwarcz/react-firebase-app
I am really new to react and firebase and I followed this tutorial to come up with this app (full project – github link here) – it's an "Add your Wish app"
My problem is that I cannot store clap count on each post to my firebase – this component is called LikeButton.js.
I have been trying to add some similar firebase code (handleChange, handleSubmit, componentDidMount... etc.. etc..) as I learned in the tutorial to LikeButton.js to store the total amount of counts in firebase each time the button is clicked and the amount of claps incremented by +1.
Simply what I want – everytime the clap button is clicked and the initial ('0') state of count is incremented to +1 the current count is going to be updated into the database.
Just cannot come up with solution, can somebody please help?
My LikeButton.js code without any firebase:
import React, { Component } from 'react'
import firebase from '../../firebase.js';
import { makeStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import './Like.css';
class LikeButton extends Component {
state = {
count: 0,
}
incrementLike = () => {
let newCount = this.state.count + 1
this.setState({
count: newCount
})
console.log(this.state.count);
}
render() {
return(
<div class="counter">
<Button type="submit" color="primary" onChange={this.handleCount} onClick={this.incrementLike}>{this.state.count} 👏</Button>
</div>
)
}
}
export default LikeButton
My Add.js code with firebase:
import React, { Component } from 'react';
import firebase from '../../firebase.js';
import Button from '#material-ui/core/Button';
import TextField from '#material-ui/core/TextField';
import FadeIn from "react-fade-in";
import Placeholder from '../Placeholder/Placeholder.js';
import LikeButton from '../Like/Like.js'
import './Add.css';
class Add extends Component {
constructor() {
super();
this.state = {
loading: true,
currentItem: '',
username: '',
items: []
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleSubmit(e) {
e.preventDefault();
const itemsRef = firebase.database().ref('items');
const item = {
title: this.state.currentItem,
user: this.state.username
}
itemsRef.push(item);
this.setState({
currentItem: '',
username: ''
});
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(json => {
setTimeout(() => this.setState({ loading: false }), 1500);
});
const itemsRef = firebase.database().ref('items');
itemsRef.on('value', (snapshot) => {
let items = snapshot.val();
let newState = [];
for (let item in items) {
newState.push({
id: item,
title: items[item].title,
user: items[item].user
});
}
this.setState({
items: newState
});
});
}
removeItem(itemId) {
const itemRef = firebase.database().ref(`/items/${itemId}`);
itemRef.remove();
}
render() {
return (
<div className="container">
<div className="wrap">
<section className="add-item">
<h1>Napíš svoj wish</h1>
<h3>Možno prilepíš sebe, možno posunieš firmu.</h3>
<form onSubmit={this.handleSubmit}>
<TextField
id="filled-required"
label="Meno"
name="username"
variant="filled"
value={this.state.username}
onChange={this.handleChange}
/>
<TextField
required
id="standard-multiline-flexible"
label="Tvoje prianie"
name="currentItem"
variant="filled"
multiline
rows="6"
rowsMax="8"
value={this.state.currentItem}
onChange={this.handleChange}
/>
<Button
type="submit"
variant="contained"
color="primary">
Poslať wish
</Button>
</form>
</section>
<section className='items-list'>
<div className="item">
<div>
{this.state.items.map((item) => {
return (
<div>
{this.state.loading ? (
<>
<FadeIn>
<Placeholder />
</FadeIn>
</>
) : (
<div className="wish" key={item.id}>
<FadeIn>
<h2>{item.title}</h2>
<div className="name">
<p>poslal <span>{item.user}</span></p>
<LikeButton />
</div>
</FadeIn>
</div>
)}
</div>
)
})}
</div>
</div>
</section>
</div>
</div>
);
}
}
export default Add
First of all, you need to tell the LikeComponent which Wish it will be updating, and you will also need to be able to access the clapCount of the wish from the LikeComponent. This can be done easily using props. You should re-configure LikeComponent to accept a prop similar to wish, which would be the wish that you are displaying and modifying.
So, this line in Add.js
<LikeButton />
would instead look like <LikeButton wish={item} />. This way, your LikeComponent can access the item/wish.
Next, in the LikeComponent, you need to remove the local state and instead use the clap count stored in Firebase. Luckily, since you're passing the wish via a prop, you can simply refactor the LikeComponent to look like this:
class LikeButton extends Component {
incrementLike = () => {
// TODO: Implement clap incrementation via Firebase updates
}
render() {
return(
<div class="counter">
<Button type="submit" color="primary" onClick={this.incrementLike}>{this.props.wish.clapCount} 👏</Button>
</div>
)
}
}
Next, we need to actually implement incrementLike. Luckily, since we are getting the wish item passed to us via the wish prop, we can easily update it like so:
incrementLike = () => {
// get a reference to the item we will be overwriting
const wishRef = firebase.database().ref(`/items/${this.props.wish.id}`);
// get the current value of the item in the database
wishRef.once('value')
.then(snapshot => {
// get the value of the item. NOTE: this is unsafe if the item
// does not exist
let updatedWish = snapshot.val();
// update the item's desired property to the desired value
updatedWish.clapCount = updatedWish.clapCount + 1;
// replace the item with `wish.id` with the `updatedWish`
wishRef.set(updatedWish);
});
}
While this should work with only a few tweaks, I'm sure there's a better way to do it. You might even be able to avoid the call to once('value') since you're passing wish as a prop to LikeComponent. You should play around with it.
However, I strongly encourage you to explore migrating to Firebase Cloud Firestore. It's API is way more straightforward (in my opinion) than Realtime Database.
I try to map the fetched data but I always get an error in my mapping because the data hasn't fetched before I use the map function. I'm able to get a get a specific element in from my fetched data using a click event.
parent class where I fetch my datas, I need the beer data for my mapping.
class App extends Component{
constructor(props){
super(props);
this.props.fetchUser();
this.props.fetchBeers();
}
class where I try to map my beers:
class BeersLanding extends Component{
getBeers = () => {
let beers= this.props.beers;
console.log(beers);
console.log(beers[0]);
console.log(beers[1]);
}
constructor(props){
super(props);
}
render(){
const {loading} =this.props;
console.log(this.props.beers)
return(
<div style={{textAlign:'center'}}>
...
<input type="text" placeholder="Search.." name="search"></input>
<button type="submit" onClick={() =>this.getBeers()} >Submit</button>
<div className={'beersContainer'}>
{this.props.beers.map((beer,index) =>(
<div className={'card'}>
hello
</div>
))}
</div>
</div>
);
}
}
Action method:
export const fetchBeers = () => async dispatch => {
const res = await axios.get('/api/beers');
dispatch({type:FETCH_BEERS, payload:res.data});
};
reducer:
export default function(state=null, action){
// console.log(action);
switch(action.type){
case FETCH_BEERS:
return action.payload;
default:
return state;
}
}
There are tow options to solve this issue, first option and I recommended to use this, by using defaultProps and set default value of bees as array.
the second option by add condition before map your data
{this.props.beers && this.props.beers.map((beer,index) =>(
<div className={'card'}>
hello
</div>
))}
I would recommend using react life cycle hooks for this type of issues.
componentDidMount() {
this.props.YOURACTIONS()
}
So this will happen when component is loaded.
I have a React container with a number of child components. One of which is supposed to be a modal that will show the user their name which is fetched from a user data api in the parent container. I should be able to pass the user data into the child with a prop, but must be missing something, as the display name does not show in the input as the value.
Parent Container
class ParentContainer extends React.Component {
constructor (props) {
super(props)
this.state = {
displayName: this.state.user.displayName
}
this.config = this.props.config
}
async componentDidMount () {
try {
const userData = await superagent.get(`/api/user`)
await this.setState({ user: userData.body })
console.log(userData.body.displayName) <===logs out user display name
} catch (err) {
console.log(`Cannot GET user.`, err)
}
}
render () {
return (
<div className='reviews-container'>
<ReviewForm
config={this.config} />
<ReviewList
reviews={reviews}
ratingIcon={this.ratingIcon}
/>
<DisplayNameModal
config={this.config}
displayName={this.displayName} />
</div>
)
}
}
export default ParentContainer
Child Component
class DisplayNameModal extends React.Component {
constructor (props){
super(props)
this.state = {
displayName: this.props.displayName
}
}
render (props) {
const {contentStrings} = this.props.config
return (
<div className='display-name-container' style={{ backgroundImage: `url(${this.props.bgImgUrl})` }}>
<h2 className='heading'>{contentStrings.displayNameModal.heading}</h2>
<p>{contentStrings.displayNameModal.subHeading}</p>
<input type="text" placeholder={this.props.displayName}/>
<button
onClick={this.submitName}
className='btn btn--primary btn--md'>
<span>{contentStrings.displayNameModal.button}</span>
</button>
<p>{contentStrings.displayNameModal.cancel}</p>
</div>
)
}
}
export default DisplayNameModal
I found that adding displayName: userData.body.displayName to setState and then wrapping the component in the parent with
{this.state.displayName &&
<div>
<DisplayNameModal
config={this.config}
displayName={this.state.displayName} />
</div>
}
works as the solution.
The prop should be passed by:
<DisplayNameModal
config={this.config}
displayName={this.state.displayName} />
where you are using:
<DisplayNameModal
config={this.config}
displayName={this.displayName} />
You have set the displayName on state in the parent, anything you refer to from state should be referred to as this.state.foo, where as any method on that component can be referred to as this.foo.
First of all, you fetch the data in wrong way, you can check it here:
componentDidMount () {
superagent.get(`/api/user`).then(res => this.setState({ user: res.body }))
}
the second one, initialize default state for displayName, for example, an empty string, it will be replaced when promise retrieves data data from the server:
constructor (props){
super(props)
this.state = {
displayName: ''
}
}
and pass this state as props to your child component:
render () {
return (
<div className='reviews-container'>
<ReviewForm
config={this.config} />
<ReviewList
reviews={reviews}
ratingIcon={this.ratingIcon}
/>
<DisplayNameModal
config={this.config}
displayName={this.props.displayName} />
</div>
)
}
in your child component, you can simply call this props:
<input type="text" placeholder={this.props.displayName}/>
I have an app that uploads files via a standard <input type="file"/>. I'm trying to pass the file size of the chosen file(s) to the child to see if it's above a certain size, and if so, display an error. I know you have to pass state values down as props, but I'm unsure as to where/how to call the function to get an updated value. Any help is appreciated.
Edit: I am using the react jsonschema form to build the form: https://github.com/mozilla-services/react-jsonschema-form. Declaring the schemas before the Parent class.
Parent
const schema = {
type: 'object',
required: ['file'],
properties: {
file: { type: 'string', format: 'data-url', title: 'File' }
}
}
const FileWidget = (props) => {
return (
<input type="file" id="fileName" required={props.required} onChange={(event) => props.onChange(event.target.value)} />
)
}
const uiSchema = {
file: {
'ui:widget': FileWidget,
classNames: "uiSchema"
}
}
class Parent extends Component {
constructor(props) {
super(props);
this.state = { fileSize: 0 };
this.getFileSize = this.getFileSize.bind(this);
getFileSize(){
this.setState({fileSize: document.getElementById("fileName").files[0].size});
console.log("FILESIZE:: ", this.state.fileSize);
} //where to call to update the file size?
render() {
return (
<div className="container">
<FileUpload schema={schema} uiSchema={uiSchema} fileSize={this.state.fileSize} />
</div>
)
}
}
export default Parent;
Child
class Child extends Component {
constructor(props) {
super(props);
this.state = { formData: {} };
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div className="container">
<Form
schema={this.props.schema}
uiSchema={this.props.uiSchema}
formData={this.state.formData}
onChange={({ formData }) => this.setState({ formData })}
onSubmit={this.handleSubmit}
>
<div>
<button type="submit" className="btn btn-info">Convert</button>
</div>
</Form>
<div hidden={this.props.fileSize > 100 ? false : true }><h4>File size exceeded.</h4></div>
</div>
)
}
}
export default Child;
class Parent extends Component {
constructor(props) {
super(props);
this.state = { fileSize: 0 };
this.getFileSize = this.getFileSize.bind(this);
getFileSize(){
this.setState({fileSize: document.getElementById("fileName").files[0].size});
console.log("FILESIZE:: ", this.state.fileSize);
} //where to call to update the file size?
componentDidMount(){
// you can call the getFilesize here
this.getFileSize();
}
render() {
return (
<div className="container">
<FileUpload fileSize={this.state.fileSize} />
</div>
)
}
}
export default Parent;
child Component
class FileUpload extends Component {
constructor(props) {
super(props);
this.state = { formData: {} };
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div className="container">
<Form
formData={this.state.formData}
onChange={({ formData }) => this.setState({ formData })}
onSubmit={this.handleSubmit}
>
<div>
<button type="submit" className="btn btn-info">Convert</button>
</div>
</Form>
<div style={{display:this.props.fileSize > 100 ? "block": "none" }><h4>File size exceeded.</h4></div>
</div>
)
}
}
export default FileUpload;
I think you want to show the error message when file size exceeds given size
you can also use componentWillMount to call getfilesize
it actually depends document.getElementById("fileName")
it that particular element has populated the data by the time your parent componentWill Mount you can use componentWillMount lifecycle hook
Parent Component
class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
onFileSelected(e) {
var fileSize = e.target.files.length > 0 ? e.target.files[0].size : false;
if (fileSize)
this.setState({ fileSize });
}
render() {
return (
<div className="App">
<input type="file" onChange={this.onFileSelected.bind(this)} />
<FileUpload fileSize={this.state.fileSize}></FileUpload>
</div>
);
}
}
child Component
class FileUpload extends Component {
render() {
return (
<div>
{this.props.fileSize > 100 ? <h2 >File size exceeds 100</h2> : null}
</div>
);
}
}
in the above code what i did is created <input type="file"/> in parent component and attached a onchange event to it.
Got it to work. Passed the function to the child:
<FileUpload fileSize={this.getFileSize.bind(this)} />
Then in the child added a setState to the form's onChange to call the function:
onChange={({ formData }) => { this.setState({ formData }); this.setState({fileSize:this.props.fileSize()})}}
and displayed the error message accordingly:
<div style={{display: this.state.fileSize > 100 ? "block": "none" }><h4>File size exceeded.</h4></div>