I am trying to create simple react js app, below is my code snippet(Notes.tsx file)
import React, { createRef, useRef } from 'react';
function NotesEditor(props: any) {
const txtNoteRef = useRef<HTMLInputElement>(null);
return (
<div className={"row"}>
<div className="col-md-6">
<div className="form-group">
<input type="text" ref={txtNoteRef} id="txtNote" className="form-control"></input>
</div>
</div>
<div className="col-md-6">
<input type="button" className="btn btn-primary" value="Save Note" onClick={handleSaveNote}></input>
</div>
</div>
);
function handleSaveNote(event: any) {
debugger
}
}
export default NotesEditor;
can someone please explain why I am getting error Uncaught ReferenceError: txtNoteRef is not defined whenever I am trying to access it in method handleSaveNote() or how can I use useref properly? below is the screenshot of the error.
i was able to resolve this error by changing line const txtNoteRef = useRef<HTMLInputElement>(null); to const txtNoteRef = useRef<any>(); and it worked!!!
import React, { createRef, useRef } from 'react';
function NotesEditor(props: any) {
const txtNoteRef = useRef<any>();
return (
<div className={"row"}>
<div className="col-md-6">
<div className="form-group">
<input type="text" ref={txtNoteRef} id="txtNote" className="form-control"></input>
</div>
</div>
<div className="col-md-6">
<input type="button" className="btn btn-primary" value="Save Note" onClick={handleSaveNote}></input>
</div>
</div>
);
function handleSaveNote(event: any) {
debugger
}
}
export default NotesEditor;
Related
I am new to react. This errors occurs. Am I using too many useState()? I have been looking at the problems many times, I don't know what happen
The Error Message
-Uncaught Error: Too many re-renders. React limits the number of renders to prevent an
infinite loop.
The above error occurred in the <App> component:
at App (http://localhost:3000/static/js/bundle.js:261:82)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
My AddMember Component.AddMember.js.Am I using too many useState here
import React, { useState } from "react";
import "../src/css/AddMember.css";
const AddMember = (props) => {
const [nameofmovie, setnameofmovie] = useState("");
const [moviepic, setmoviepic] = useState("");
const [leadActor, setleadActor] = useState("");
const [rating, setRating] = useState("");
function onChangeName(event) {
setnameofmovie(event.target.value);
}
function onChangeImage(event) {
setmoviepic(event.target.value);
}
function onChangeActor(event) {
setleadActor(event.target.value.split(","));
}
function onChangeRating(event) {
setRating(event.target.value);
}
const transferValue = (event) => {
event.preventDefault();
const val = {
name: nameofmovie,
"picture of image": moviepic,
"lead actor": leadActor,
rating: rating,
};
props.onSubmitHandler(val);
clearState();
};
const clearState = () => {
setnameofmovie("");
setmoviepic("");
setleadActor("");
setRating("");
};
return (
<div>
<div id="topFormLayerOne">
<form>
<div id="secondFormLayerTwo">
<label id="labelTwo">Please key in the Id</label>
<input
id="inputThree"
type="text"
maxLength="10"
placeholder="Please key in the Id"
></input>
<label id="labelFour">Movie Names</label>
<input
onChange={onChangeName}
id="inputFour"
type="text"
maxLength="100"
placeholder="Movies Names"
name="moviesName"
></input>
<label id="labelFive">Picture of Movies</label>
<input
onChange={onChangeImage}
id="inputFive"
type="file"
maxLength="100"
placeholder="Name of Images"
name="imageName"
></input>
<label id="labelSix">Lead Actor Names</label>
<input
onChange={onChangeActor}
id="inputSix"
type="text"
maxLength="500"
placeholder="Name of Actor"
name="actorName"
></input>
<label id="labelSeven">Rating</label>
<input
onChange={onChangeRating}
id="inputSeven"
type="text"
maxLength="10"
placeholder="Rating"
name="movieRating"
></input>
<button onClick={transferValue} id="submitButton">
Submit
</button>
<button id="removeButton">Remove Movie</button>
</div>
</form>
</div>
</div>
);
};
export default AddMember;
My Member Component.Member.js
import React from "react";
function Members({data}) {
const tableRows = (data) => (data.map((info) => {
return(
<tr key={info.id}>
<td>{info.id}</td>
<td>{info.name}</td>
<td><img src={info["picture of image"]} alt=""></img><
<td>
{info["lead actor"]}
</td>
<td>{info.rating}</td>
</tr>
)
}))
return (
<div>
<table className="table table-stripped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Image</th>
<th>Actors</th>
<th>Rating</th>
</tr>
</thead>
<tbody>{tableRows}</tbody>
</table></div>
);
}
export default Members;
My App Component.My App.js
import dataMovielist from '../src/data/data.json';
import Members from './Members';
import AddMember from './AddMember';
import {useState} from 'react';
function App() {
const [datalist, setdatalist] = useState(dataMovielist);
const onSubmitHandler = ((newHobbies)=>{
setdatalist((oldHobbies)=>[newHobbies,...oldHobbies])
})
return (
<div className="App">
<AddMember onSubmitHandler = {onSubmitHandler()} />
<Members data={datalist} />
</div>
);
}
export default App;
I don't know what happen. Can you help me solve it
I think it's this line:
<AddMember onSubmitHandler = {onSubmitHandler()} />
You probably meant to write <AddMember onSubmitHandler={onSubmitHandler} /> The parentheses are causing the function to be invoked immediately as opposed to onSubmit. This is likely triggering a chain reaction.
Also, you want to change this line:
<tbody>{tableRows}</tbody>
to
<tbody>{tableRows(data)}</tbody>
to avoid "Functions are not valid a React child" error.
There are two components
WelcomePage.jsx
import { useState } from "react";
import SignUpPage from "./SignUpPage";
function WelcomePage() {
const [signUp, toSignUp] = useState(false);
function signUpClick() {
toSignUp(true);
}
return (
<div>
{signUp ? (
<SignUpPage isOpen={signUp} />
) : (
<div
className="Welcome_page__container animate__animated animate__fadeIn"
id="welcome_page"
>
<h1 className="Welcome_page__title">Welcome to Hotel Review </h1>
<h3 className="Welcome_page__subtitle">Sign in :</h3>
<div className="Welcome_page__wrapper">
<label className="Welcome_page__input-title" htmlFor="welcome_mail">
E-mail:
</label>
<input
className="Welcome_page__input"
id="welcome_mail"
type="mail"
placeholder="Your e-mail..."
/>
<label className="Welcome_page__input-title" htmlFor="welcome_pass">
Password:
</label>
<input
className="Welcome_page__input"
id="welcome_pass"
type="text"
placeholder="Your password..."
/>
<button className="Welcome_page__btn">Login</button>
<button className="Welcome_page__btn" onClick={signUpClick}>
Sign Up
</button>
</div>
</div>
)}
</div>
);
}
export default WelcomePage;
SignUpPage.jsx
function SignUpPage() {
return (
<div className="Welcome_page__container animate__animated animate__fadeIn">
<button>Back...</button>
<h1 className="Welcome_page__title">Welcome to Hotel Review </h1>
<h3 className="Welcome_page__subtitle">Sign up :</h3>
<div className="Welcome_page__wrapper">
<label className="Welcome_page__input-title" htmlFor="welcome_mail">
E-mail:
</label>
<input
className="Welcome_page__input"
id="welcome_mail"
type="mail"
placeholder="Your e-mail..."
/>
<label className="Welcome_page__input-title" htmlFor="welcome_pass">
Password:
</label>
<input
className="Welcome_page__input"
id="welcome_pass"
type="text"
placeholder="Your password..."
/>
<label
className="Welcome_page__input-title"
htmlFor="welcome_pass"
></label>
<input
className="Welcome_page__input"
id="welcome_pass_repeat"
type="text"
placeholder="Repeat password..."
/>
<button className="Welcome_page__btn_2">Sign Up</button>
</div>
</div>
);
}
export default SignUpPage;
Clicking the "Sign Up" button in WelcomePage.jsx using useState navigates to SignUpPage.jsx
Question - How can I return back to WelcomePage.jsx on the "Back" button (I understand that I need to return false back to const [signUp, toSignUp] = useState() , but I don't know how to transfer state from WelcomePage to SignUpPage and vice versa.)
You can pass it via props from parent to child component.
And pass the setState from child component to parent.
import { useState } from "react";
import SignUpPage from "./SignUpPage";
function WelcomePage() {
const [signUp, setSignUp] = useState(false);
function signUpClick() {
toSignUp(true);
}
return (
<>
{signUp ? (
<SignUpPage isOpen={signUp} setOpen={setSignUp} />
) : (
<div>
... component
</div>
)
</>
);
}
export default WelcomePage;
function SignUpPage(props) {
const { isOpen, setOpen } = props;
return (
<>
{isOpen}
<button onClick={setOpen(true)}>Open</button>
<button onClick={setOpen(false)}>Close</button>
</>
);
}
export default SignUpPage;
I have this modal window component. The problem is that when I want to submit some of the modal window props, an error occurs because of the line below:
<form className="modal-content-sizes-form" onSubmit={(e)=>{cartStore.handleSubmitForm(e,{**pizzaStore**.modalProps.name, **pizzaStore**.modalProps.description, **pizzaStore**.size, **pizzaStore**.price, **pizzaStore**.modalProps.ImageUrl})}}>
So the question is, what is wrong with writing pizzaStore.modalProps.name? Because this doesn't let the app compile
Here is the full code of the component:
import React from 'react'
import pizzaStore from './stores/PizzaStore'
import {observer} from "mobx-react-lite"
import cartStore from './stores/CartStore';
import { action } from 'mobx';
function ModalWindowComponent({activeModal, setActiveModal}:any){
const [selectedOption, setSelectedOption]=React.useState("small")
const handleSetOption=(e:any)=>{
setSelectedOption(e.target.value);
pizzaStore.setSize(selectedOption);
pizzaStore.setPrice(selectedOption)
}
return (
<div className={activeModal?"modal active":"modal"} onClick={()=>{setActiveModal(false); setSelectedOption("small")}}>
<div className="modal-content" onClick={(e)=>{e.stopPropagation()}}>
<div className="modal-content-header">
<button onClick={()=>setActiveModal(false)}>Close</button>
</div>
<img src={pizzaStore.modalProps.modalImageUrl} className="modal-content-img"/>
<p className="modal-content-pizza-name">{pizzaStore.modalProps.name}</p>
<p className="modal-content-pizza-desc">{pizzaStore.modalProps.description}</p>
<p className="modal-content-pizza-size">{pizzaStore.size}см</p>
<p className="modal-content-pizza-weight">{pizzaStore.setWeight(selectedOption)}грамм</p>
<p className="modal-content-pizza-price">{pizzaStore.price}Руб.</p>
<form className="modal-content-sizes-form" onSubmit={(e:any)=>{cartStore.handleSubmitForm(e,{pizzaStore.modalProps.name, pizzaStore.modalProps.description, pizzaStore.size, pizzaStore.price, pizzaStore.modalProps.ImageUrl})}}>
<label>
<input name="radio-size"value="small" type="radio" onChange={handleSetOption} checked={!activeModal||selectedOption==="small"} className="modal-content-sizes-form-option"/>Маленькая</label>
<label>
<input name="radio-size"value="medium" type="radio" onChange={handleSetOption}checked={selectedOption==="medium"}className="modal-content-sizes-form-option"/>Средняя</label>
<label>
<input name="radio-size"value="big" type="radio" onChange={handleSetOption}checked={selectedOption==="big"} className="modal-content-sizes-form-option"/>Большая</label>
<button onClick={()=>{setActiveModal(false);console.log(cartStore.cartItems, pizzaStore.price)}}>Добавить</button>
</form>
</div>
</div>
)
}
export default observer(ModalWindowComponent)
I'm trying to run this in react but it showing me error:
path.split is not a function
import React from 'react'
import './SendMail.css'
import CloseIcon from '#material-ui/icons/Close'
import { Button } from '#material-ui/core'
import { useForm } from 'react-hook-form'
function SendMail() {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = (data) => {
console.log(data)
}
return (
<div className="sendMail">
<div className="sendMail_header">
<h3>New Message</h3>
<CloseIcon className="sendMail_close"/>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<input
name='to'
placeholder="To"
type="text"
ref = {register({required:true})}
/>
<input
name='subject'
placeholder="Subject"
type="text"
/>
<input
name='message'
placeholder="Message.."
type="text"
className="sendMail_message"
/>
<div className="sendMail_options">
<Button className="sendMail_send"
variant="contained"
color="primary"
type="submit"
>
Send
</Button>
</div>
</form>
</div>
)
}
Export default SendMail
I am trying to display a checkbox when the add button is clicked but it refuses to display. Take a look at the addTask() function and you will see what I am trying to do. Thank you, in advance!
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask()}>Add</button>
</div>
</div>
</div>
</div>
);
}
addTask() {
var tasks = document.getElementById('task');
localStorage.setItem('user-task', tasks);
return(
<input type="checkbox" label={localStorage.getItem('user-task')} />
)
}
}
export default MainPage;