Delete the entire div including subdiv's on clicking the remove button - html

I am new to reactjs development and I'm trying real hard to delete the entire division including sub divisions on clicking "remove" button. The addition of entire div is working smoothly, but I am not sure how can I perform deletion of entire div on clicking remove button.
class Createloc extends Component {
constructor(props) {
super(props);
this.state = {
count: 1,
rows: [],
}
this.addRow = this.addRow.bind(this)
this.deleteRow = this.deleteRow.bind(this)
}
// divID = nextId();
addRow() {
this.setState({ count: this.state.count + 1 })
console.log(`Increase count: ${this.state.count}`)
};
deleteRow(e) {
// ==> not sure
// console.log("delete");
};
addingDivs() {
let count = this.state.count, uiItems = [];
while (count--)
uiItems.push(
<div className="newHost" id={this.divID}>
<div className="hostInput">
<input type="text" placeholder="Enter Building Name" />
</div>
<div className="hostInput">
<input type="text" placeholder="Enter Employee Name" />
</div>
<div className="hostInput">
<button className="btn btn-danger" type="button" onClick={this.deleteRow}>Remove</button>
</div>
</div>
)
return uiItems;
}
render() {
return (
<form className="form">
<div className="addButton">
<button type="button" onClick={this.addRow}>Add</button>
{this.addingDivs()}
</div>
</form>
)
}
}
export default Createloc;
PS: I have not included the pseudo I tried to delete just to avoid confusion.

I was able to delete the added row as a stack by applying below:
deleteRow(e) {
this.setState({ count: this.state.count - 1 })
};
Thanks!

Related

React - HTML form validation doesn't work

I work on a React project. I wrote HTML codes for create form. There is validation in HTML scripts. I wrote validations but validations doesn't work. The code is below. For example I want the relevant field to be red when the name is not entered or I want it to give a warning message when the name does not comply with the text rules. I must do it without any library. How can I fix it ?
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';
class CreateEmployeeComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
}
componentDidMount(){
if(this.state.id === '_add'){
return
}else{
EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
let employee = res.data;
this.setState({firstName: employee.firstName,
lastName: employee.lastName,
emailId : employee.emailId
});
});
}
}
saveOrUpdateEmployee = (e) => {
e.preventDefault();
let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('employee => ' + JSON.stringify(employee));
// step 5
if(this.state.id === '_add'){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
changeFirstNameHandler= (event) => {
this.setState({firstName: event.target.value});
}
changeLastNameHandler= (event) => {
this.setState({lastName: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({emailId: event.target.value});
}
cancel(){
this.props.history.push('/employees');
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
onSubmit = e => {
e.preventDefault();
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form onSubmit={this.onSubmit} noValidate>
<div className = "form-group">
<label for="validationCustom01" class="form-label">First name</label>
<input type='text' maxLength={20} pattern='[A-Za-z]' placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstNameHandler} required/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input type='text' maxLength={20} pattern='[A-Za-z]'class="form-control" placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastNameHandler} required/>
</div>
<div className = "form-group">
<label> Email Id: </label>
<input type='email' maxLength={35} pattern='[A-Za-z]' placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmailHandler} required/>
</div>
<button type="submit" className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateEmployeeComponent
Remove noValidate from your <form> element.
Additionally, I've personally found that Formik and Yup can be a helpful library.
(Sorry I missed that "no libraries" wasa constraint)
Edit:
I was a muppet and forgot to change the pattern
You can do one of 2 things:
Remove maxLength and change the pattern to pattern="[A-Za-z]{1,20}"
Where 20 will be the new max-length (so 20 or 35, depending on the field)
Only change the pattern to be pattern="[A-Za-z]+"
The + is needed to ensure 1 or more of the [A-Za-z] regex is done. https://regexr.com/
Also don't forget to remove noValidate from your <form> element.
This answer may also prove helpful in setting custom validity status messages and callbacks.

React js a problem about updating the state value [duplicate]

This question already has answers here:
Why does calling react setState method not mutate the state immediately?
(9 answers)
Closed 2 years ago.
i'am just a newbie at React , i'am trying to make a form , when submitting i call a function "handleSubmit" that saves all the information into the state, and then displaying it into a grid , but it wont work for some reasons .
i really do need your help : here is my code :
export default class products extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state =
{
QrCode: ''
}
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
data.set('username', data.get('username').toUpperCase());
this.setState({QrCode: data});
console.log(this.state);
}
render() {
return (
<div >
<div >
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<button>Send data!</button>
</form>
</div>
<div style={{margin: '10%', marginTop : '5%'}}>
<GridComponent dataSource={this.state} />
</div>
</div>
);
}
}
and here what i get :
i keep getting empty array
and thank you.
In React, you don't need use form to take values from inputs.
export default class App extends React.Component {
constructor() {
super();
this.state = {
userName: ""
};
}
render() {
return (
<div className="App">
<label htmlFor="username">Enter username</label>
<input
value={this.state.userName}
onChange={e => this.setState({ userName: e.target.value })}
name="username"
type="text"
/>
<button
onClick={() => {
alert(this.state.userName);
}}
>
Send data!
</button>
</div>
);
}
}
Hope it help you!

json object is not effecting to view

I am using angular Formio for dynamic screen creation, as part of that when I get the screen script from database, if I change the label of the particular element in ngOnInit() I am able to change.
but once the screen is displayed, then if I change the lable it is not effecting.
html
<Formio [form]="form" [submission]="submission" (submit)="onSubmit($event)"></formio>
<div class="mb-5">
<div class="row">
<div class="col-12 mb-5">
<div class="pull-right" style="float:right;">
<button class="btn save-button" (click)="clearData()">Clear data</button>
<button class="btn save-button" (click)="showData()">Show data</button>
</div>
</div>
</div>
</div>
component
ngOnInit() {
debugger;
this.triggerRefresh = new EventEmitter();
this.http.get('http://localhost:3000/angcomp/3')
.subscribe(
response => {
debugger;
this.data = response.json();
this.form = this.data;
this.form.components[0].label = 'Changed';//it is updating the lable in view
},
err => {console.error(err)}
);
}
showData() {
this.form.components[0].label = 'Again Changed'; // here it is not changing but in this.form.components[0].label value is displaying as 'Again Changed', but not effecting in front end
}
Try the refresh property in formio
In yout HTML:
<Formio [refresh]="triggerRefresh" [form]="form" [submission]="submission" (submit)="onSubmit($event)"></formio>
In your component:
showData() {
this.form.components[0].label = 'Again Changed';
this.triggerRefresh.emit({
form: this.form
});
}
https://github.com/formio/angular-formio/wiki/Form-Renderer#updating-forms-and-submissions

Passing a html value as a parameter in react

I need to pass a html value as a parameter for my function like so:
<input type ="text" placeholder="Smart Contract Bytecode" name="name" id ="scbytecode"className="nice-textbox"/>
<button id="button" onClick={parseAddress("document.getElementById('smartcontract').value)"}>Submit!</button>
but Im getting an error:
TypeError: Cannot read property 'value' of null
here is the Full code.
Added this to give a better impression of whats going on cause the fixes below don't seem to fix it all. Any help is welcomed.
class App extends Component {
parseAddress(_smartcontract){
var contractObj = new ethweb3.eth.Contract(ERC20ABI, document.getElementById('smartcontract').value);
contractObj.getPastEvents(
'Transfer' || 'allEvents',
{
fromBlock: 0,
toBlock: 'latest'
},
function(err,res){
console.log(err,res);
//examples to access the data returned
console.log(res.length);
document.getElementById("totalAddresses").innerHTML = res.length;
document.getElementById("sampleAddress").innerHTML = res[0].returnValues.from;
document.getElementById("sampleAmount").innerHTML = res[0].returnValues.value;
}
);
}
deploSC = async () => {
const accounts = await goweb3.eth.getAccounts();
//const code = ethweb3.eth.getCode(document.getElementById('smartcontract').value); Not working
console.log(code);
goweb3.eth.sendTransaction({
from: accounts[0],
data: document.getElementById('scbytecode').value
}, function(error, hash){
console.log(error,hash);
});
}
render() {
return (
<div className="App">
<header className="App-header">
<p>
Enter the smart contract address:
<input type="text" name="name" id="smartcontract" className="nice-textbox"/>
<input type ="text" placeholder="Sc bytecode" name="name" id ="scbytecode"className="nice-textbox"/>
<button id="button" onClick={this.parseAddress}>Submit!</button>
<button onClick={this.deploSC}> Deploy Sc</button>
</p>
<p id="totalAddresses">0</p>
<p id="sampleAddress">0</p>
<p id="sampleAmount">0</p>
</header>
</div>
);
}
}
export default App;
There is a better way to do this in React using state and not directly accessing the DOM which should be avoided.
Store the value of an input in the component's state, then give it to the button's onClick event handler via this.state.inputVal.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inputVal: ''
};
}
inputChanged = (e) => {
this.setState({ inputVal: e.target.value });
}
render() {
return (
<div>
<input type ="text" placeholder="Smart Contract Bytecode" name="name" id ="scbytecode" className="nice-textbox" onChange={this.inputChanged}/>
<button id="button" onClick={() => { console.log(this.state.inputVal); }}>Submit!</button>
</div>
);
}
}
// Render it
ReactDOM.render(
<App/>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I think there is mismatch in id.
line 1 you gave "scbytecode"
line 2 you are trying access by id "smartcontract" which is not present, so you are seeing null

Toggle between the visibility of 2 divs in reactjs

I have a simple reactjs website hosted on GitHub Pages. It lists articles, something like feeds in reddit. I have an AddArticle requirement, wherein, upon clicking the 'Add Article' button on the bottom of the page, the Div containing this button must become hidden, and a new Div for adding the details of the article(containing 2 text-boxes and a button named 'Submit') must show up. Upon clicking the 'Submit' button, the earlier Div has to reappear with the new Div getting hidden.
The following is the code I currently use(that is incomplete). Please go through it and provide any insight into the problem. Thanks.
class Child extends React.Component {
constructor(props) {
super(props);
this.onClickSubmitButton = this.onClickSubmitButton.bind(this);
this.state = {
showing: false
};
}
onClickSubmitButton(){
console.log('test-2');
this.setState(
{
showing: true
}
);
}
render() {
const { showing } = this.state;
return (
<div id="div_2">
<br/>
<input type="text" placeholder="Add the article title here" className="block_text"></input>
<br/><br/>
<input type="text" placeholder="Add the article text here" className="block_text"></input>
<br/><br/>
<button
type="button"
onClick={() =>
this.onClickSubmitButton()}
>
Submit
</button>
{ showing
? <div>This is visible</div>
: null
}
</div>
);
}
}
export default class AddArticle extends React.Component {
constructor(props) {
super(props);
this.onClickAddButton = this.onClickAddButton.bind(this);
this.state = {
error: undefined,
tempArticle: undefined,
childVisible: false,
parentVisible: true
};
}
onClickAddButton(){
console.log('test-1');
this.setState(
prevState => (
{
childVisible: !prevState.childVisible,
parentVisible: !prevState.parentVisible
}
)
);
}
// this is the render method
render() {
return (
<div id="div_1">
<br/><br/>
<button
type="button"
onClick={() =>
this.onClickAddButton()}
>
Add Article
</button>
{
this.state.childVisible
? <Child />
: null
}
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Here is a solution. You should had just send prop to the <Child /> component
DEMO