React- Lodash without() method rendering empty after state change? - javascript

I am new to React and I have run into some difficulty I cannot seem to figure out.
I am using Lodash to remove a single object from an array, via an onClick eventHandler. However once I select to delete a specific item, the display is rendered as empty, However When I console.log the returned Array it shows the elements are present but wrapped in a lodashWrapper.
Also the element I selected for removal is still in the Array.
I am using the lodash method without and I have included all relevant snippets.
class App extends Component
{
constructor()
{
super();
this.state =
{
appointments : [],
idx : 0,
}
this.deleteAppointment = this.deleteAppointment.bind(this)
}
deleteAppointment(apt)
{
let temp = this.state.appointments;
console.log(temp);
temp = without(temp,apt)
console.log(temp);
this.setState({
appointments : temp
});
}
<ListAppointment appointments = {this.state.appointments}
deleteAppointment={this.deleteAppointment} />
class ListAppointment extends Component
{
render()
{
return (
<div className="appointment-list item-list mb-3">
{this.props.appointments.map(item =>(
<div className="pet-item col media py-3" key={item.aptID}>
<div className="mr-3">
<button className="pet-delete btn btn-sm btn-danger"
onClick={()=> this.props.deleteAppointment(item)} >
<FaTimes />
</button>
</div>
Any insight as to why this is occurring is greatly appreciated. I have tried different formats to Bind this but i still end with the same result, which is an empty array being rendered.
Thanks in Advance

Related

can't append h1 element to parent div in React?

i'm creating a simple react website that's supposed to do some calculations and find out Joules of my input values after the calculations...right now the input values are already preset but i will remove the value="" from my <input> later.
here is the .JSX component file that's the issue...one of the components.
import React, { Component } from 'react';
import Atom_icon from './cartridges.png';
class Joule_calc extends Component {
render(){
return (
<div className='Joule_div'>
<h3 style={{color:"white", textAlign:"center"}}>JOULE CALCULATOR</h3>
<label className='lab1'>WEIGHT=/GRAMS</label><br></br>
<input className='weight_inp' type='text' value="2" />
<label className='lab2'>SPEED=M/S</label><br></br>
<input className='speed_inp' type='text' value="5" />
<button className='count_button' onClick={this.Create_response}>CALCULATE</button>
<h1 className='Result_joule'></h1>
</div>
)
}
Create_response(){
console.log("creating response...")
let sum = document.createElement("h1")
sum.className = 'Result_joule'
sum.textContent = "678"
let div_panel = document.getElementsByClassName("Joule_div")
div_panel.append('Result_joule')
}
Returned_values(){
let weight_val = document.getElementsByClassName("weight_inp")[0].value;
let speed_val = document.getElementsByClassName("speed_inp")[0].value;
let final_calculation = weight_val * speed_val
return final_calculation
}
}
export default Joule_calc
so when i run my code i get
Uncaught TypeError: div_panel.append is not a function
at Create_response (Joule_calc_window.jsx:31:1)
i don't get why i can't append my new element to the div. it says it's not a function so what's the solution then? i'm new to React and web so probably it's just a noobie thing.
also i tried directly creating a h1 inside the 'Joule_div' like this.
<h1 className='Result_joule'>{"((try returning here from one of these methods))"}</h1>
but that of course failed as well. So would appreciate some help to get what's going on. i'm trying to add a number after the button click that's in h1 and in future going to be a returned number after calculating together the input values in a method.i imagine that something like
MyMethod(){
value = values calculated
return value
}
and later grab it with this.MyMethod
example
<h1>{this.MyMethod}</h1>
this is a example that of course didn't work otherwise i wouldn't be here but at least gives you a clue on what i'm trying to do.
Thank you.
You don't leverage the full power of react. You can write UI with only js world thanks to JSX. State changes triggering UI update.
I may miss some specificaiton, but fundamental code goes like the below. You should start with function component.
// Function component
const Joule_calc = () =>{
// React hooks, useState
const [weight, setWeight] = useState(0)
const [speed, setSpeed] = useState(0)
const [result,setResult] = useState(0)
const handleCalculate = () =>{
setResult(weight*speed)
}
return (
<div className="Joule_div">
<h3 style={{ color: 'white', textAlign: 'center' }}>JOULE CALCULATOR</h3>
<label className="lab1">WEIGHT=/GRAMS</label>
<br></br>
<input className="weight_inp" type="text" value={weight} onChange={(e)=>setWeight(parseFloat(e.target.value))} />
<label className="lab2">SPEED=M/S</label>
<br></br>
<input className="speed_inp" type="text" value={speed} onChange={(e)=>setSpeed(parseFloat(e.target.value))} />
<button className="count_button" onClick={handleCalculate}>
CALCULATE
</button>
<h1 className='Result_joule'>{result}</h1>
</div>
)
}
export default Joule_calc;
div_panel is an collection of array which contains the classname ["Joule_div"]. so first access that value by using indexing . and you should append a node only and your node is "sum" not 'Result_joule' and you should not use textcontent attribute because you will be gonna definitely change the value of your result as user's input value
Create_response(){
console.log("creating response...")
let sum = document.createElement("h1")
sum.className = 'Result_joule'
//sum.textContent = "678"
let div_panel = document.getElementsByClassName("Joule_div")
div_panel[0].append('sum')
}
if any problem persists , comment below

How to implement an array increment function within JSX code using React.js JavaScript

I'm trying to develop a React program that changes information in a component each time the button "rectForward" or "rectBackward" is pressed. I'm passing the information in the form of an array of objects into my Body component from "importData" as seen below. That data is then converted into each object's indvidual data pieces through the map functions listed directly after render() is called. What I want to happen when the rectForward button is pressed is for the "text1" array value in Column1 to incrament by 1. The same happens when rectBackward is pressed, but I want the value to decrement. My primary difficulty is the syntax. As you can see in the statement onClick={Column1.text1=text1val[++], this was my first attempt at implementing this functionality, but the syntax is definitely incorrect. I was wondering if I could get some help formatting this
import React from "react";
import "./Body.css";
import Column1 from "./Body/Column1/Column1";
import "./Buttons.css";
import Column2 from "./Body/Column2/Column2";
import myData from "./myData";
class Body extends React.Component {
constructor() {
super()
this.state = {
importData: myData
}
}
render() {
var ID = this.state.importData.map(item => item.id)
var text1val = this.state.importData.map(item => item.text1)
var text2val = this.state.importData.map(item => item.text2)
var text3val = this.state.importData.map(item => item.text3)
return(
<div className="mainBody">
<div className="backPain">
<div className="holder">
<Column1 key={ID[0]} text1={text1val[0]}>
</Column1>
<div className="rectHolder">
<div className="rectForward" onClick={Column1.text1=text1val[++]}
<h2>Next</h2>
</div>
<div className="rectBackward">
<h2>Prev</h2>
</div>
</div>
<Column2 key={ID[0]} text2={text2val[0]} text3={text3val[0]}>
</Column2>
</div>
</div>
</div>
)
}
}
export default Body;
Thanks so much!
Simple thing i will do is keep an index in state. Than pass a function to next and prev which takes care of changing this index. and will show the values based on current state.
this.state = {
currentIndex : 0
}
HandleCurrentIndex(type){
if(type === 'inc'){
this.setState({currentIndex: this.state.currentIndex++})
} else {
this.setState({currentIndex: this.state.currnIndex-1 })
}
}
<div className="rectForward" onClick={()=>this.HandleCurrentIndex("inc")}>
<h2>Next</h2>
</div>
<div className="rectBackward" onClick={()=>this.HandleCurrentIndex('dec')}>
<h2>Prev</h2>
</div>
On side note:- This is just and example in product you should take care of index going below zero as well index exceeding limits of your data. which in turn will show undefined values. simple thing you should do is whenever it goes out of limit just reset it to default value ( 0 )

react.js how to get prop form tree element

I am trying to make table cell editable after clicking on icon in another cell , for that I need to get index of element so the editor will open in the correct row , which icon belongs to.
My issue is that I dont know the way i should get the prop value of table DOM element here is code for for clearify
a part of dom tree generated with react:
<tbody>
{stepsDone.map(function(step,idx) {
let content = step;
const editing = this.state.editing;
if(editing){
content = (
<form onSubmit={this._save}>
<input type="text" defaultValue={step} />
</form>
);
}
return(
<tr key={idx}>
<td className="step" data-step={'step'+idx}>{content}</td>
<td className="icRow">
<Icon className="edit" onClick={this._showEditor} rownum={idx}/>
<Icon className="remove"/>
<Icon className="trash outline"/>
</td>
</tr>
)
},this)}
show editor function:
_showEditor(e){
this.setState({
editing:{
row:e.target.rownum
}
});
console.log(this.state.editing);
}
After execution of showedtior function console logs :
first click = null , which is normal i think
more clicks = undefined , and thats whats brings a trouble i want to receive idx from map function.
here is code from Icon.js
import React from 'react';
import classNames from 'classnames';
export function Icon(props) {
const cssclasses = classNames('icon', props.className);
return <i className={cssclasses} onClick={props.onClick}/>;
}
if you want to reveive the idx from the map function you should pass it to the function _showEditor so your code must be like this :
<Icon className="edit" onClick={this._showEditor(idx)}/>
and the function definition should be :
_showEditor = (idx) => (event) => {
this.setState({
editing:{
row:idx
}
});
console.log(this.state.editing);
}
or if you don't want to use the arrow functions for some reason, just replace
onClick={this._showEditor(idx)}
with
onClick={this._showEditor.bind(this,idx)}
and its definition becomes
_showEditor(idx){...}

creating elements in React

I don't understand how elements are created in React.
I have some code below where the goal is to create elements on a form submit using a value from a refs - so for every submit in a form, it creates a new <h1> tag with the content of the textbox inside of it. A sample of what I'm trying to do looks like:
...
addHeader(e) {
e.preventDefault();
const newHeader = this.refs.post.value;
var newpost = React.createElement("h1", {
type: "text",
value: newHeader
});
}
...
render() {
return (
<div className="form-section">
{ newPost }
<form onSubmit={this.addHeader.bind(this)}>
<input id="input-post" type="text" placeholder="Post Here" ref="post" />
<input type="submit" value="Submit" />
</form>
<button className="form-section__submit" onClick={this.clearFields.bind(this)}>Clear All</button>
</div>
);
}
Basically my thinking is in my addHeader() function I'm assigning a variable of newPost to the method and calling it within my component. This code is causing 2 errors:
33:9 warning 'newpost' is assigned a value but never used no-unused-vars
49:13 error 'newPost' is not defined no-undef
What I don't understand, is (from what I can see) I am assigning a value to that variable and also using it in the component that I am rendering... along with that, I don't understand this error message. How can something be assigned a value but be undefined at the same time...? Is it because it's in the wrong scope? How do I declare where the new element is rendered specifically in the component?
I read the documentation but it doesn't give a clear answer as to how to control where in the component the new element is rendered.
Made some changes to your code. You're going to want to initialize component state in your constructor. In your addHeader method you will use this.setState to update the state of the component with a new posts value including the value of this.input. I changed your ref on the input an actual ref. You take the element and store on this. Every time you add a new post you will get a new <h1> with the value of the textarea.
...
addHeader(e) {
e.preventDefault();
this.setState((prevState, props) => {
return { posts: [ ...prevState.posts, this.input.value ] };
});
}
...
render() {
const { posts } = this.state;
return (
<div className="form-section">
{ posts.map( text => <h1>{ text }</h1> ) }
<form onSubmit={this.addHeader.bind(this)}>
<input id="input-post" type="text" placeholder="Post Here" ref={ el => this.input = ref } />
<input type="submit" value="Submit" />
</form>
<button className="form-section__submit" onClick={this.clearFields.bind(this)}>Clear All</button>
</div>
);
}
As an aside: Binding functions in the render method of react components will cause a performance hit. There is no need to re-bind the this context of the function on every render. this.clearFields.bind(this) should become this.clearFields and you will need to add this.clearFields = this.clearFields.bind(this) to your constructor. You do not need to bind functions that are not used as callbacks.
You're going to want to do the same thing for this.addHeader.bind(this).

Conditional rendering of a static partial in react - MERN

I am trying to figure out how to conditionally render a partial in react. My condition is that when a list item is active, the partial should be rendered.
I am using bootstrap, which has an active element available for use.
My goal is to achieve something similar to intercom's terms page: https://www.intercom.com/terms-and-policies#billing
In my main menu, I have:
import React from 'react';
import ReactDOM from 'react-dom';
var Terms = require('../overview/terms.jsx');
var Privacy = require('../overview/privacy.jsx');
var Cookies = require('../overview/cookies.jsx');
var Thirdparty = require('../overview/thirdparty.jsx');
var Website = require('../overview/website.jsx');
var Sla = require('../overview/sla.jsx');
var Acceptable = require('../overview/acceptable.jsx');
var Billing = require('../overview/billing.jsx');
var Information = require('../overview/information.jsx');
var Incident = require('../overview/incident.jsx');
var Bug = require('../overview/bug.jsx');
class Menu extends React.Component {
render() {
return (
<div>
<div className = "row">
<div className = "col-md-8 col-md-offset-2 generalhead">
Terms and Policies
</div>
</div>
<div className = "row">
<div className = "col-md-3 col-md-offset-1">
<ul className="list-group">
Terms of Service
Privacy Policy
Cookies
Third Party Processors
Website Use
Service Level Agreement
Acceptable Use
Billing
Information Security
Incident Response Plan
Bug Bounty
</ul>
</div>
<div className = "col-md-6 col-md-offset-1">
<Terms />
<Privacy />
<Cookies />
<Thirdparty />
<Website />
<Sla />
<Acceptable />
<Billing />
<Information />
<Incident />
<Bug />
</div>
</div>
</div>
);
}
}
module.exports = Menu;
Each list item has a named data attribute. When that attribute is the active item, I want to then render the partial. At the moment all of them are rendering.
I have read the react docs on conditional rendering: https://facebook.github.io/react/docs/conditional-rendering.html
I was trying to define a const called active that I thought might make use of the bootstrap class - but that isn't working. I must have the wrong end of the stick for how to do this. I seems like a simple hide show for a rails js toggle. I can't figure out how to get started on tackling this in react.
Can anyone give me a steer in the right direction?
Keep track of which list item is active in your state
<a href="#" onClick={() => this.setState({active: 'terms'})}>Terms of Service</a>
Then conditionally only render the active item
{this.state.active == 'terms' && <Terms />}
But I suggest using react router instead since each item seems to correspond to a page.
Edit
You have to add a constructor to your class to make it stateful
class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
};
}
.
.
.

Categories

Resources