button Onclick call the function with React State - reactjs

I am new to react,
I am trying to pass the values on the button onclick from one component to another.
Here is my following code:
contact Component:
import React,{useState} from 'react';
import Section from '../../../HOC/Section';
import apicall from '../../UI/JS/allapicall.js';
const Contact = () => {
const [name, setName] = useState(0);
console.log("name");
return (
<Section id='contact'>
<div className='container pt-2 pb-5'>
<div className='section-header pt-5 pb-5 text-center'>
<h3 className='section-title'>
<span>Get in touch with </span>Us
</h3>
<h6 className='section-subtitle mr-auto ml-auto'>
We are here with you
</h6>
</div>
<div className='section-content'>
<div className='row'>
<div className='col-md-9 col-lg-7 mr-auto ml-auto'>
{/* <form> */}
<div className='form-group'>
<input
type='text'
className='form-control rounded-0'
aria-describedby='emailHelp'
placeholder='Enter Name...'
onChange={e=>setName(e.target.value)}
/>
</div>
<div className='form-group'>
<input
type='email'
className='form-control rounded-0'
aria-describedby='emailHelp'
placeholder='Enter email...'
/>
</div>
<div className='form-group'>
<textarea
className='form-control rounded-0'
rows='5'
placeholder='Enter Message...'
/>
</div>
<div className='form-group text-center'>
<button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={apicall({name})}>
Send
</button>
</div>
{/* </form> */}
</div>
</div>
</div>
</div>
</Section>
);
};
export default Contact;
apicall.js:
export default function messagesubmit(test)
{
console.log(test);
const axios = require('axios');
// Optionally the request above could also be done as
axios.get('https://www.zohoapis.com/crm/v2/functions/ticket_create/actions/execute?auth_type=apikey', {
params: {
zapikey: "1003.9145fb5d691b5f95a194c17e56300ed3.1cc7246813d8d6842c47f543a4f50b8f"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
Currently:
For each state changes(when I change the "Value" of the text field) the onClick button function is calling on react, and the console.log(test); is printing for every change in name, I don't know where I am doing wrong I need to trigger it on only onclick event.
Here is what I wanted:
For each field value, I need to store the values in states.
On button Click I need to pass the stored values in the state to message submit function within an argument,
Thanks in advance

<button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={apicall({name})}>
Send
</button>
Change this to:
<button className='btn btn-block btn-primary rounded-0 mr-auto ml-auto' onClick={() => apicall({name})}>
Send
</button>

Your button's onClick needs to be () => apicall({name}) instead of just apicall({name}). When you set the onClick to be apicall({name}) then what happens is apicall({name}) gets instantly called and the onClick is set to the result of that call.

Related

react uploaded file needs to be re-uploaded in order to be detected

import React from 'react'
import {useState} from 'react'
const Upload = () => {
const [song, setSong] = useState({
title: '',
audio_file: null,
genre: '',
})
const [audio, setAudio] = useState(null)
const handleChange = (e) => {
const newState = { ...song, [e.target.name]: e.target.value}
setSong(newState)
}
const handleAudio = (e) => { // putting file into audio, then putting it in song
setAudio(e.target.files[0])
setSong({audio_file: audio})
}
const uploadSong = (e) => {
e.preventDefault()
console.log(song)
}
return (
<>
<form onSubmit={uploadSong}>
<section className="upload">
<div className="upload-content">
<h4>Upload Music</h4>
<input type="file" name="music" id='song' className='hidden' onChange={handleAudio}/>
<label for='song' className='btn'>Select Music</label>
</div>
</section>
<section className="info">
<div className="info-content">
<h2>Upload Info</h2>
<div className="info-visual">
<div className="info-single">
<p>Audio File</p>
{audio ? <p className='green'>{audio.name}</p> : <i className='fas fa-times' />}
</div>
<div className="info-single">
<p>Title {song.title ? <i className='fas fa-check' /> : <i className='fas fa-times' /> }</p>
<input type="text" placeholder="Enter a Title..." name='title' onChange={handleChange}/>
</div>
<div className="info-single">
<p>Size</p>
{audio ? <p class='green'>{`${(audio.size / 1000000).toString().substr(0,3)} MB`}</p> : <i className='fas fa-times' />}
</div>
<div className="info-single">
<p>Genre {song.genre ? <i className='fas fa-check' /> : <i className='fas fa-times' />}</p>
<input type="text" placeholder="Enter a Genre..." name='genre' onChange={handleChange}/>
</div>
{song.title && audio.lenght > 0 && song.genre ?
<button className="btn" type='submit'>Continue</button> : <button className="btn green">Please fill in the fields</button>}
</div>
</div>
</section>
</form>
</>
)
}
export default Upload
Basically when I try to upload the file (which is sent to {audio} and then {song} in the {handleAudio} function) and fill in the fields the button doesn't change accordingly but when I re-upload the file it gets inserted in the {song} object located at the very top and the button changes.
you should the the following:
setAudio(e.target.files[0])
setSong({audio_file: e.target.files[0]})
due to how react works if you do setAudio the value will not change until the component re render again
so access it will be wrong cause you get the previous value.
think about this
useState -> re-render -> state is updated with the new value
this is also the reason why only after re-insert you get the new value
For your information:
React 18 will introduce a new feature call batch update the will update your start with a group of useState and not only one by one

First key press is not working by using react hook form controlled component

I used react hook form for validations purpose. but our code is implemented on controlled components. I went through few examples in google that use default value instead of value.
If I replace the value with the default value after submitting a form. The values in the form are not clearing can anyone suggest to me how to overcome this.
import React, { useState, useEffect } from 'react';
import { getIdToken } from '../Utils/Common';
import { useForm } from 'react-hook-form';
export default function Roles() {
const [roleName, setroleName] = useState('');
const { register, handleSubmit, errors } = useForm();
const handleRoleName = (event) => {
setroleName(event.target.value);
};
const handleAddRole = () => {
/* api call here after succes i have clear role name*/
setroleName('');
};
}
return (
<div className='g-pa-20'>
<h1 className='g-font-weight-300 g-font-size-28 g-color-black g-mb-28'>
{editaddLabel}
</h1>
<form noValidate onSubmit={handleSubmit(handleAddRole)}>
<div className='row'>
<div className='col-md-4 col-xs-12 col-sm-12'>
<div className='g-brd-around g-brd-gray-light-v7 g-rounded-4 g-pa-15 g-pa-20--md g-mb-30'>
<div className='mb-4'>
<div className='form-group g-mb-30'>
<label className='g-mb-10' for='inputGroup-1_1'>
Role Name
</label>
<div
className={
errors && roleName === ''
? 'g-err-brd-primary--focus'
: 'g-pos-rel'
}
>
<span className='g-pos-abs g-top-0 g-right-0 d-block g-width-40 h-100 opacity-0 g-opacity-1--success'>
<i
className='hs-admin-check g-absolute-centered g-font-size-default g-color-secondary'
on
></i>
</span>
<input
id='inputGroup-1_1'
className='form-control form-control-md g-brd-gray-light-v7 g-brd-gray-light-v3--focus g-rounded-4 g-px-14 g-py-10'
type='text'
placeholder=''
onChange={handleRoleName}
value={roleName}
name='role'
ref={register({
required: true,
})}
/>
</div>
{errors.role && errors.role.type === 'required' && (
<p className='plans-single-error'> Role name is required.</p>
)}
</div>
</div>
<div className='from-group'>
<div className='form-row pull-right'>
<div className='form-group col-xs-6'>
<button
className='btn btn-md btn-xl--md u-btn-primary g-font-size-12 g-font-size-default--md g-mr-10 g-mb-10'
disabled={loading}
>
{loading && (
<i className='fas fa-spinner fa-spin spinner'></i>
)}
Save
</button>
</div>
<div className='form-group col-xs-6'>
<button
className='btn btn-md btn-xl--md u-btn-outline-gray-dark-v6 g-font-size-12 g-font-size-default--md g-mb-10'
onClick={cancelClick}
>
Cancel
</button>
</div>
</div>
</div>
<div className='from-group'>
<label></label>
</div>
</div>
</div>
</div>
</form>
</div>
);

How to pass a Child component state to Parent Component state in React

I am working on a React project, In my project I have two components Studentslist and Card.
In Studentslist component I have two buttons, one is Hockey and another one is Cricket.
Now when I click the Cricket button, then only Card component will show I have written logic like
That. Here Card component is Child to Studentslist component. In that Card component I have two
Buttons they are submit and cancel. Here when I click the cancel button on Card component the
Card component has to hide, but its not working. I think I have to write logic like this I have
To write one function in Card component and I have to pass that function to Studentslist
Component and that function have to update the state of the Student list component.
Please help me to solve this
If you feel I am not clear with my doubt, please put a comment.
This is Studentslist.js
import React, { useState } from 'react';
import './Studentslist.css';
import Card from '../../Components/Card/Card';
function Studentslist() {
const [show, setShow] = useState(false);
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='Departments'>
<button className='btn btn-primary'>Hockey</button>
<button onClick={() => setShow(true)} className='btn btn-primary ml-2'>Cricket</button>
</div>
{show && <Card></Card>}
</div>
</div>
</div>
)
}
export default Studentslist
This is Card.js
import React, { useState } from 'react';
import './Card.css';
function Card() {
const [show, hide] = useState(true)
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-6'>
<div className='Registration'>
<form>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" id="firstname"></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" id="lastname"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" id="email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" id="password"></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
<button type="button" onClick={() => hide(false)} className='cancel btn btn-danger ml-2'>Cancel</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Card
you can not pass children state to parent, you can pass setShow to cardComponent as props
{show && <Card setShow={() => setShow(false)}></Card>}
and in cardComponent you can use like below
function Card({ setShow }) {
...
<button type="button" onClick={setShow} className='cancel btn btn-danger ml-2'>Cancel</button>

React update state showing other component

I have react form state. After submitting the form I want to send the input values to other component and then showing to browser. I successfully submit the form but when I sent the porps to other component. It does not show anything.
Here is my hero component
import React from "react";
import "./App.css";
import Show from "./Show";
function App() {
const [state, setState] = React.useState({
input: " ",
text: " "
});
const changeHandler = e => {
setState({ ...state, [e.target.id]: e.target.value });
};
const handleSubmit = e => {
e.preventDefault();
console.log(state);
return <Show show={state} />; //this is the component where I am sending props
};
return (
<React.Fragment>
<div className="row">
<form className="col s12" onSubmit={handleSubmit}>
<div className="row">
<div className="input-field col s3">
<input
id="input"
type="text"
data-length="4"
onChange={changeHandler}
/>
<label htmlFor="input_text">Input text</label>
</div>
</div>
<div className="row">
<div className="input-field col s8">
<textarea
id="text"
className="materialize-textarea"
data-length="120"
onChange={changeHandler}
></textarea>
<label htmlFor="textarea2">Right your text</label>
</div>
</div>
<button
className="btn waves-effect blue lighten-1"
type="submit"
name="action"
>
Submit
</button>
</form>
<Show /> //After submit the form I want to show to the browser
</div>
</React.Fragment>
);
}
export default App;
Here is my child component.
import React from "react";
export default function Show({ show }) {
return (
<div>
{show ? (
<ul>
<li>{show.input}</li>
<li>{show.text}</li>
</ul>
) : null}
</div>
);
}
ps: Ignore this message.In order to upload this post I need to. write more 😀.
Calling Method was wrong
handleSubmit is the event activity call .its not component
Inside the handleSubmit component return is not right one
So better pass state value on Show component inside the parent fragment
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
return (
<React.Fragment>
<div className="row">
<form className="col s12" onSubmit={handleSubmit}>
<div className="row">
<div className="input-field col s3">
<input
id="input"
type="text"
data-length="4"
onChange={changeHandler}
/>
<label htmlFor="input_text">Input text</label>
</div>
</div>
<div className="row">
<div className="input-field col s8">
<textarea
id="text"
className="materialize-textarea"
data-length="120"
onChange={changeHandler}
></textarea>
<label htmlFor="textarea2">Right your text</label>
</div>
</div>
<button
className="btn waves-effect blue lighten-1"
type="submit"
name="action"
>
Submit
</button>
</form>
<Show show={state} /> //pass state directly
</div>
</React.Fragment>
);

How to push new FieldArray from outside render function?

I have this code to push new FieldArray every time I click the button, but it is only applicable inside renderContract FieldArray component.
const renderContact = ({ fields, meta: { error } }) => (
<div>
{fields.map((contact, index) => (
<div key={index}>
<div className="row form-pad">
<div className="col-md-3">
<span>Country Code {index + 1}:<span className="requiredField text-danger"> * </span>: </span>
</div>
<div className="col-md-7">
<Field name={`${contact}.landlineCountryCode`} component={renderField}type="text"/>
</div>
</div>
</div>
))}
<button className="btn btn-primary" onClick={() => fields.push({})}>
Add Contact
</button>
</div>
)
and render it like this on parent form component:
<FieldArray name="contact" component={renderContact} />
How can I use fields.push({}) outside fieldArray?
EDIT:
I tried this but to no avail:
<button type="button" onClick={() => props.dispatch(arrayPush('PersonalInfoForm', 'contact', [{}]))}> Add Contact</button>
You can dispatch an action arrayPush with the form and the fieldname to effect a fields.push({}) from outside the FieldArray
import { arrayPush } from 'redux-form';
// ...
dispatch(arrayPush('myForm', 'contact', {}));

Resources