I have a form with steps name, email, util.
When a have input I can get the value inserts, but when a have input button with options true or false, I can't get the values.
This is my code:
class CreateData extends Component {
state = {
step: 1,
nome:'',
email:'',
util: '',
}
nextStep = () => {
const { step } = this.state
this.setState({
step : step + 1
})
}
prevStep = () => {
const { step } = this.state
this.setState({
step : step - 1
})
}
handleChange = input => event => {
this.setState({
[input] : event.target.value,
})
}
renderSwitch(step) {
const { nome, email, util } = this.state;
const values = { nome, email, util};
switch (step) {
case 1:
return <UserName
nextStep = {this.nextStep}
handleChange = {this.handleChange}
values = {values}
/>
case 2:
return <UserEmail
nextStep = {this.nextStep}
prevStep = {this.prevStep}
handleChange = {this.handleChange}
values = {values}
/>
case 3:
return <UserUtil
nextStep = {this.nextStep}
prevStep = {this.prevStep}
handleChange = {this.handleChange}
values = {values}
/>
case 4:
return <CrossHomePage/>
}
}
render() {
const {step} = this.state;
return (
<div>
<HeaderPage />
{this.renderSwitch(step)}
</div>
);
}
}
export default CreateData
In my component to get name is ok:
class UserName extends Component{
saveAndContinue = (e) => {
e.preventDefault()
this.props.nextStep()
}
render(){
const { values } = this.props;
return(
<Grid className={style.container}>
<Form>
<fieldset>
<input
className="input"
onChange={this.props.handleChange('nome')}
defaultValue={values.nome}
type="text"
required
/>
</fieldset>
<Button className="button" onClick={this.saveAndContinue}> Continue </Button>
</Form>
</Grid>
)
}
}
export default UserName;
But in my component to get button value doesn't work, I want to get the value of the button clicked.
<input
type="button"
className="input"
onChange={values.moradia[1]}
value='yes'
defaultValue={values.util}
onClick={ this.saveAndContinue }
/>
<input
type="button"
className="input"
onChange={values.util}
value='no'
defaultValue={values.util}
onClick={ this.saveAndContinue }
/>
How I do get the value of the button clicked in this case and save this value to invoke in another component?
Example here.
I want to get value of buttons yes or no
https://codesandbox.io/s/r1lm9j22l4
Using event.target.value
Add value property to Button
<Button className="button" value="continue" onClick={this.saveAndContinue}> Continue </Button>
saveAndContinue = (e) => {
e.preventDefault();
console.log(e.target.value); //will give you the value continue
this.props.nextStep();
}
Related
Good day so I have a question about firebase and perhaps my code as well I wrote some code in JSX and React linked to Firebase and the Button that I'm using to delete is not working properly.
I'm using Parent Child props to pass the function into the page that is needed to be deleted but there is no functionality. I need help thanks!
this is the parent where the function is located :
import React from 'react';
import fire from '../config/firebase';
import Modal from 'react-modal';
// import "firebase/database";
// import 'firebase/auth';
import NotesCard from './note-card';
Modal.setAppElement('#root');
export default class Notes extends React.Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
notes: [],
showModal: false,
loggedin: false
};
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleAddNote = this.handleAddNote.bind(this);
this.handleRemoveNote = this.handleRemoveNote.bind(this);
}
componentDidMount() {
this._isMounted = true;
fire.auth().onAuthStateChanged((user) => {
if(user){
// call firebase from import fire
// grab userData and push it to the dataArray
fire.database().ref(`users/${user.uid}/notes`).on('value', (res) => {
const userData = res.val()
const dataArray = []
for(let objKey in userData) {
userData[objKey].key = objKey
dataArray.push(userData[objKey])
}
// set in the state
if(this._isMounted){
this.setState({
notes: dataArray,
loggedin: true
})
}
});
}else {
this.setState({loggedin: false})
}
});
};
componentWillUnmount() {
this._isMounted = false;
}
handleAddNote (e) {
e.preventDefault()
const note = {
title: this.noteTitle.value,
text: this.noteText.value
}
// reference where we can push it
const userId = fire.auth().currentUser.uid;
const dbRef = fire.database().ref(`users/${userId}/notes`);
dbRef.push(note)
this.noteTitle.value = ''
this.noteText.value = ''
this.handleCloseModal()
}
handleRemoveNote(key) {
const userId = fire.auth().currentUser.uid;
const dbRef = fire.database().ref(`users/${userId}/notes/${key}`);
dbRef.remove();
}
handleOpenModal (e) {
e.preventDefault();
this.setState({
showModal: true
});
}
handleCloseModal () {
this.setState({
showModal: false
});
}
render() {
return (
<div>
<button onClick={this.handleOpenModal}>create Note</button>
<section className='notes'>
{
this.state.notes.map((note, indx) => {
return (
<NotesCard
note={note}
key={`note-${indx}`}
handleRemoveNote={this.handleRemoveNote}
/>
)
}).reverse()
}
</section>
<Modal
isOpen={this.state.showModal}
onRequestClose={this.handleCloseModal}
shouldCloseOnOverlayClick={false}
style={
{
overlay: {
backgroundColor: '#9494b8'
},
content: {
color: '#669999'
}
}
}
>
<form onSubmit={this.handleAddNote}>
<h3>Add New Note</h3>
<label htmlFor='note-title'>Title:</label>
<input type='text' name='note-title' ref={ref => this.noteTitle = ref} />
<label htmlFor='note-text'>Note</label>
<textarea name='note-text' ref={ref => this.noteText = ref} placeholder='type notes here...' />
<input type='submit' onClick={this.handleAddNote} />
<button onClick={this.handleCloseModal}>close</button>
</form>
</Modal>
</div>
)
}
}
and this is where the function is being called :
import React from 'react';
import fire from '../config/firebase';
export default class NotesCard extends React.Component {
constructor(props) {
super(props);
this.state = {
editing: false,
note: {}
}
this.handleEditNote = this.handleEditNote.bind(this);
this.handleSaveNote = this.handleSaveNote.bind(this);
}
handleEditNote() {
this.setState({
editing: true
})
}
handleSaveNote(e) {
e.preventDefault()
const userId = fire.auth().currentUser.uid;
const dbRef = fire.database().ref(`users/${userId}/notes/${this.props.note.key}`);
dbRef.update({
title: this.noteTitle.value,
text: this.noteText.value
})
this.setState({
editing: false
})
}
render() {
let editingTemp = (
<span>
<h4>{this.props.note.title}</h4>
<p>{this.props.note.text}</p>
</span>
)
if(this.state.editing) {
editingTemp = (
<form onSubmit={this.handleSaveNote}>
<div>
<input
type='text'
defaultValue={this.props.note.title}
name='title'
ref={ref => this.noteTitle = ref}
/>
</div>
<div>
<input
type='text'
defaultValue={this.props.note.text}
name='text'
ref ={ref => this.noteText = ref}
/>
</div>
<input type='submit' value='done editing' />
</form>
)
}
return (
<div>
<button onClick={this.handleEditNote}>edit</button>
<button onClick={this.props.handleRemoveNote(this.state.note.key)}>delete</button>
{editingTemp}
</div>
)
}
}
Thank you in advance for taking a look at this code.
Second iteration answer
Working sandbox
Problem
looking at https://codesandbox.io/s/trusting-knuth-2og8e?file=/src/components/note-card.js:1621-1708
I see that you have this line
<button onClick={()=> this.props.handleRemoveNote(this.state.note.key)}>delete
Yet your state.note declared as an empty map in the constructor:
this.state = {
editing: false,
note: {}
}
But never assigned a value using this.setState in the component
Solution
Change it to:
<button onClick={()=> this.props.handleRemoveNote(**this.props.note.key**)}>delete</button>
First iteration answer
NotesCard's buttons is firing the onClick callback on render instead on click event.
This is because you have executed the function instead of passing a callback to the onClick handler
Change
<button onClick={this.props.handleRemoveNote(this.state.note.key)}>delete</button>
To
<button onClick={()=> this.props.handleRemoveNote(this.state.note.key)}>delete</button>
I'm trying to make a multi-step form using React.js and material UI. for validation purpose I am using Joi-Browser. But I am getting error from Joi while validation, stating that error: ValidationError: "value" must be an object
I am very new to React.js Please guide me what I am doing wrong here.
here what I have tried so far.
class ServiceRequestForm extends Component {
state = {
step: 1,
service_category: [],
user : [
{
full_name: '',
address_one: '',
}
],
hasError: false
}
schema = Joi.object().keys({
full_name: Joi.string().alphanum().min(3).max(100).required(),
address_one: Joi.string().required(),
});
validate = () => {
const result = Joi.validate(this.state.user, this.schema)
console.log(result)
}
// Proceed to next step
nextStep = () => {
const { step } = this.state;
this.setState({
step: step + 1
});
}
// Proceed to prev step
prevStep = () => {
const { step } = this.state;
this.setState({
step: step - 1
});
}
// handle select
handleChange = (event)=> {
this.setState(oldValues => ({
...oldValues,
[event.target.name]: event.target.value,
}));
}
// handle input
handleChangeInput = name => event => {
this.setState({ [name]: event.target.value });
};
handleSubmit = ()=>{
this.validate();
}
render() {
const { step } = this.state;
const { service_category } = this.state;
const { full_name, address_one } = this.state.user;
const values = { service_category, full_name, address_one };
switch (step) {
case 1:
return (
<CategoryForm
nextStep={this.nextStep}
handleChange={this.handleChange}
values={values}
/>
);
case 2:
return (
<AddressForm
prevStep={this.prevStep}
handleChangeInput={this.handleChangeInput}
handleSubmit={this.handleSubmit}
values={values}
/>
);
case 3:
return (
<ThankYouPage
/>
);
}
}
}
export default ServiceRequestForm;
// Category form
export default class CategoryForm extends Component {
continue = e => {
e.preventDefault();
this.setState({ hasError: false });
if (!this.props.values.service_category) {
console.log(this.props.hasError);
this.setState({ hasError: true });
}
else {
this.props.nextStep();
}
}
render() {
const { handleChange, values, classes, nextStep, hasError } = this.props;
return (
<div>
<h4>Select service you want</h4>
<form>
<FormControl error={hasError}>
<Select
value={values.service_category}
onChange={handleChange}
inputProps={{
name: 'service_category'
}}
>
<MenuItem value="">
<em>Select Category</em>
</MenuItem>
<MenuItem value={10}>House Maid</MenuItem>
<MenuItem value={20}>Electricians</MenuItem>
<MenuItem value={30}>Plumber</MenuItem>
</Select>
<FormHelperText>Please select service category</FormHelperText>
{hasError && <FormHelperText>This is required!</FormHelperText>}
</FormControl>
</form>
<br />
<Button variant="contained" color="primary" onClick={this.continue}>Next</Button>
</div>
)
}
}
// address form
export default class AddressForm extends Component {
back = e => {
e.preventDefault();
this.props.prevStep();
}
render() {
const { handleChangeInput, values, classes, handleSubmit, prevStep, hasError, full_name } = this.props;
return (
<div>
<h1>Address</h1>
<TextField
label="Full Name"
//className={classes.textField}
value={values.full_name}
onChange={handleChangeInput('full_name')}
margin="normal"
variant="outlined"
/>
<TextField
label="Address Line 1"
//className={classes.textField}
value={values.address_one}
onChange={handleChangeInput('address_one')}
margin="normal"
variant="outlined"
/>
<Button variant="contained" color="primary" onClick={handleSubmit}>Submit</Button>
<Button variant="contained" color="primary" onClick={prevStep}>Back</Button>
</div>
);
}
}
Schema can be just an object.
Try using like below.
{
full_name: Joi.string().alphanum().min(3).max(100).required(),
address_one: Joi.string().required(),
}
No need to specify
Joi.object().keys(
When I click my Add Category button, nothing happens. I want to be able to add tasks and add new categories. When I add a category, the category should be added to the category array list and attached to the tasks array.
I have tried to create an addCats(e) function and added to the Add Category button's on click.
class TaskBar extends React.Component
{
constructor(props){
super(props);
this.state = {
tasks:[],
task: '',
categories:["Home","Work","Play","X"],
cats: ''
};
this.addTask = this.addTask.bind(this);
this.addCats = this.addCats.bind(this);
}
addCats(e){
if(this.state.cats !=="")
{
var newCategory = {
text: this.state.cats,
key: Date.now(),
};
this.setState(() => {
this.state.categories.push(newCategory);
});this.setState({cats: ''});
}
}
addTask(e){
// console.log(this.state.task);
if(this.state.task !== "")
{
var newTask = {
text: this.state.task,
key: Date.now(),
categories:[]
};
this.setState(() => {
this.state.tasks.push(newTask);
});
this.setState({task: ''});
// console.log(this.state.task);
}
//console.log(this.state.tasks);
}
componentDidUpdate(){
console.log(this.state.tasks);
console.log(this.state.categories)
}
render(){
return (
<div className="inputArea cols-md-6">
<input
value = {this.state.task}
placeholder = "Enter task"
onChange = {(event) => this.setState({task:event.target.value})}
/>
<input type="button" value="Add Task" onClick={this.addTask} />
<br /><br />
<input
value = {this.state.cats}
placeholder = "Add Category"
onChange = {(event) => this.setState({cats:event.target.value})}
/>
<input type="button" value="Add Category" onClick={this.addCats} />
<br /><br />
<div>
<TaskList tasks={this.state.tasks} categories={this.state.categories}/>
</div>
</div>
)
}
}
export default TaskBar;
When I click Add Category,the page refreshes but displays nothing.
when you need to add category you must keep last data in array and add new data to array so in this case
function CategoryMain() {
const [dataCategory,setDataCategory] = useState([]);
const [text,setText] = useState('')
const addItem = ()=>{
const newItem = [...dataCategory];
const newData = {
id:newItem.length + 1,
title:text,
}
setDataCategory([...newItem,newData ])
setText('')
}
return(
<div>
<button onClick={addItem}>add Category</button>
</div>
)
}
<!-- begin snippet: js hide: false console: true babel: false -->
I'm creating an input element using document.createElement and setting the attribute. i would like to have an onchange event which will update the state.
how can i proceed? following is my code
addoffers = () => {
var input = document.createElement("input");
input.setAttribute('name', 'whatweoffer'.concat(Math.floor((Math.random() * 1000) + 1)));
input.setAttribute('class','form-control mb-3');
input.setAttribute('placeholder','what we offer');
input.onchange = this.handleChange;
var parent = document.getElementById("offerinput");
parent.appendChild(input);
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(e.target.value);
}
<input type="text" className="form-control mb-3" id='whatweoffer' name='whatweoffer' onChange={this.handleChange} placeholder='what we offer' required />
Try this
class DynamicInputs {
constructor(props) {
super(props);
this.state = {
inputs : []
}
}
render() {
return (
<React.Fragment>
{
this.state.inputs.map(inputValue =>{
<input key= {inputValue} type="text" placeholder="what we offer" className="form-control mb-3" name = {`whatweoffer${inputValue}`} onChange = {this.handleChange} required/> })
}
</React.Fragment>
)
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(e.target.value);
}
addInput() = () =>{
let {inputs} = this.state;
inputs.push((Math.floor((Math.random() * 1000) + 1))
this.setState({
inputs
})
}
}
Although there's accepted answer but I want to give you another approach.
Instead of create input dynamically, why don't you just use own component's state to decide if an input is displayed or not, and other attributes are just state values. For example:
render() {
const {
isInputDisplayed, inputName, inputId, inputClasses, inputPlaceholder,
} = this.state;
return (
{ isInputDisplayed && (
<input type="text" name={inputName} id={inputId} className={inputClasses} placeholder={inputPlaceholder} />
)}
);
}
Given a react form with multiple radio buttons and a text input that is visible only when the other option radio button is selected, I currently have the submit button disabled until a radio button is selected. However, if the other option is selected, the submit button will still work even if there is no text in the input field associated with it. How can I check the length of the input box if and only if the other option is selected?
class CancelSurvey extends React.Component {
constructor (props) {
super(props)
this.state = {
reasons: [],
reason: {},
otherReasonText: undefined,
submitting: false
}
this.processData = this.processData.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.setReason = this.setReason.bind(this)
this.setOtherReasonText = this.setOtherReasonText.bind(this)
this.otherReason = {
reason_id: 70,
client_reason: 'other'
}
}
componentDidMount () {
this.fetchSurvey()
}
/**
* Fetch reasons
*/
fetchSurvey (cb) {
superagent
.get('/api/user/survey')
.then(this.processData)
}
processData (data) {
this.setState({ reasons: data.body })
}
async handleSubmit (e) {
e.preventDefault()
await this.setState({ submitting: true })
const { reason, otherReasonText } = this.state
superagent
.post('/api/user/survey')
.send({
optionId: reason.reason_id,
optionText: reason.client_reason,
otherReasonText
})
.then(async (data) => {
await this.setState({ submitting: false })
if (data.body.success) {
this.props.setStep(OFFER)
}
})
}
setOtherReasonText (e) {
this.setState({ otherReasonText: e.target.value })
}
setReason (reason) {
this.setState({ reason })
}
/**
* render
*/
render (props) {
const content = this.props.config.contentStrings
const reasons = this.state.reasons.map((reason, i) => {
return (
<div
className='form-row'
key={i}>
<input type='radio'
id={reason.reason_id}
value={reason.client_reason}
name='reason'
checked={this.state.reason.reason_id === reason.reason_id}
onChange={() => this.setReason(reason)} />
<label htmlFor={reason.reason_id}>{reason.client_reason}</label>
</div>
)
})
return (
<div className='cancel-survey'>
<form className='cancel-survey-form'>
{ reasons }
<div className='form-row'>
<input
type='radio'
id='other-option'
name='reason'
onChange={() => this.setReason(this.otherReason)} />
<label htmlFor='other-option'>
Other reason
</label>
</div>
{ this.state.reason.reason_id === 70 &&
<div>
<input
className='valid'
type='text'
id='other-option'
name='other-text'
placeholder="placeholder"
onChange={this.setOtherReasonText} />
</div>
}
<div className='button-row'>
<button
disabled={!this.state.reason.client_reason}
className={btnClassList}
onClick={this.handleSubmit}>
<span>Submit</span>
</button>
</div>
</form>
</div>
)
}
}
export default CancelSurvey
disabled={
!this.state.reason.client_reason
||
(this.state.reason.client_reason === 'other' && !this.state.otherReasonText)
}
If you want to make sure otherReasonText is not just empty spaces, use otherReasonText: '' as initial state then check !this.state.otherReasonText.trim().
Do some conditional logic before like:
const reasonId = this.state.reason.reason_id;
const otherReasonText = this.state.otherReasonText;
const clientReason = this.state.reason.client_reason;
const shouldDisableButton = !clientReason || (reasonId === 70 && otherReasonText.length === 0)
...
<div className='button-row'>
<button
disabled={shouldDisableButton}
className={btnClassList}
onClick={this.handleSubmit}>
<span>Submit</span>
</button>
</div>