I am sorry for asking this, since I think this has been asked before. However I do not understand react enough, or at all to understand the answers people have given on other questions. Neither to implement them into the code I have.
this is the main code:
import React from 'react';
import ReactDOM from 'react-dom';
import TodoItem from './components/TodoItem';
class App extends React.Component {
componentWillMount() {
this.setState({todoList: [], inputField: ''});
}
handleInput(event) {
this.setState({inputField: event.target.value});
}
addTodo(event) {
if(this.state.inputField.length === 0 || event.keyCode && event.keyCode !== 13) return;
event.preventDefault();
var newTodo = {
text: this.state.inputField,
created_at: new Date(),
done: false
};
var todos = this.state.todoList;
todos.push(newTodo);
this.setState({todoList: todos, inputField: ''});
}
render() {
return (
<div>
<ul>
{
this.state.todoList.map(function(todo, index){
return (
<TodoItem todo={todo} key={index} />
);
})
}
</ul>
<div>
<label htmlFor="newTodo">Add Todo item</label>
<input name="newTodo" value={this.state.inputField} type="text" onKeyUp={this.addTodo.bind(this)} onChange={this.handleInput.bind(this)} />
<button type="button" onClick={this.addTodo.bind(this)} >Add</button>
</div>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
and this is the other part:
import React from 'react';
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.state = {todo: props.todo};
}
toggleDone(event) {
var currentTodo = this.state.todo;
if (currentTodo.done) {
currentTodo.done = false;
} else {
currentTodo.done = true;
}
this.setState({todo: currentTodo});
}
removeTodo(event) {
event.preventDefault();
var todos = this.state.todoList;
todos.remove(this);
}
render() {
return (
<li>
<input type="checkbox" onChange={this.toggleDone.bind(this)} />
<span className={this.state.todo.done ? 'done' : ''} >
{this.state.todo.text}</span>
<button type="button" onClick={this.removeTodo.bind(this)}
>X</button>
</li>
);
}
}
export default TodoItem;
Firstly I had the remove function in the main code, but I got an uncaught type error than because it couldn't find the bind??
And when I put it in the second part of code, I get a cannot read property "remove" of undefined error.
Any help would be awesome!
Thx upfront
Remove removeTodo function from TodoItem component and put it in App component. Pass this function as prop to TodoItem component and call this function at cross button click. Remember, bind removeTodo function to App component after moving it.
Related
I'm new to React. I'm trying to do simple validation of a form elements. I'm stuck at validating input data and setting the 'name_error' state as the error msg inside <p> tag. Leaving my code below
// App.js
import React, { Component } from 'react';
import ValidateName from './component/validation';
import Modal from './modal';
class Home extends Component {
state = {
show: false,
name: "",
name_error: ""
}
handleChanges = (e) => {
const name = e.target.name;
const value = e.target.value;
this.setState({[name] : value})
}
render() {
console.log(this)
return (
<div>
<div className='Main'>
{/* < Main /> */}
<button id='add' onClick={()=>{this.setState({show: true})}}>Add</button>
</div>
{this.state.show &&
<Modal>
<form>
<div className='modalContainer'>
<b className='title'>Register</b>
<button id='xmark' onClick={()=>{this.setState({show: false})}} >×</button>
<label for='name' >Name</label><br />
<input type="text" id='name' placeholder='Enter your name here' name="name" onChange={this.handleChanges}/><br />
< ValidateName content={this.state.name} />
<button type='submit'>Sign Up</button>
<button>Cancel</button>
</div>
</form>
</Modal>}
</div>
);
}
}
export default Home;
// Modal.js
import React, { Component } from 'react';
class Modal extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default Modal;
//validation.js
class ValidateName extends Component {
err1 ='Please enter any name';
err2 = 'Use only letters in this field';
render() {
const ren = this.props.content.length === 0 ? (<p>{this.err1}</p> ) :
(this.props.content.match(/[a-zA-Z]+$/) ? '' : <p>{this.err2}</p>)
return ren;
}
}
Please suggest an idea to set name_error as 'Please enter any name' or 'Use only letters in this field' when user enters wrong input
State should be like this,
constructor(props){
super(props);
this.state = {
show: false,
name: "",
name_error: ""
}
}
And Also the update state using callback. It would be helpful,
this.setState({[name] : value},() =>{console.log(this.state)})
I have been creating a react js project which is a task list. However I have been facing an error, for some reason I have found multiple errors. First for debugging purposes I created a handle delete function which will log a string to the console to show that it has been triggered. It is only meant to be triggered when the X button on the task element is clicked, however, it triggers whenever I submit the text input to create a new task. Secondly the biggest error is that the first element is always undefined no matter what I type. How do I fix this problem.
import React, { Component } from "react";
import ReactDOM from "react-dom";
import TaskList from "./index2";
class Tests extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
object: {},
object2: [],
};
this.updateInputValue = this.updateInputValue.bind(this);
this.submit = this.submit.bind(this);
}
updateInputValue(evt) {
this.setState({
value: evt.target.value,
});
}
submit() {
if (this.state.value.trim() != "") {
this.setState({
object: { task: this.state.value.trim(), id: Date.now },
object2: [...this.state.object2, this.state.object],
value: "",
});
} else {
return;
}
}
render() {
return (
<div>
<label for="text">Text 1</label>
<br />
<input
type="text"
label="text"
onChange={(evt) => this.updateInputValue(evt)}
onSubmit={this.submit}
value={this.state.value}
/>
<br />
<button onClick={this.submit} style={{ height: 50, width: 60 }}>
Submit
</button>
<br></br>
<TaskList
allTasks={this.state.object2}
handleDeleteFunction={console.log("handle delete has been triggered")}
/>
</div>
);
}
}
export default Tests;
ReactDOM.render(<Tests />, document.getElementById("root")
);
And my taskList code
import React from "react";
import "./woah.css";
export default function TaskList({ allTasks, handleDeleteFunction }) {
return (
<ul>
{allTasks.map(({ task, id }) => (
<li key={id} id="task">
<p>{task}</p>
<button onClick={() => handleDeleteFunction}>X</button>
</li>
))}
</ul>
);
}
Try this:
submit() {
if (this.state.value.trim() != "") {
const newObj = { task: this.state.value.trim(), id: Date.now };
this.setState({
object: newObj,
object2: [...this.state.object2, newObj],
value: "",
});
} else {
return;
}
}
You are referencing the current object in state, which is empty.
I want to display a different component with each button click.
I'm sure the syntax is wrong, can anyone help me? The browser doesn't load
I would love an explanation of where I went wrong
One component (instead of HomePage) should display on the App component after clicking the button. Help me to understand the right method.
Thanks!
App.js
import React, {useState} from 'react';
import './App.css';
import Addroom from './components/Addroom.js'
import HomePage from './components/HomePage.js'
function App() {
const [flag, setFlage] = useState(false);
return (
<div className="App">
<h1>My Smart House</h1>
<button onClick={()=>{setFlage({flag:true})}}>Addroom</button>
<button onClick={()=>{setFlage({flag:false})}}>HomePage</button>
{setState({flag}) && (
<div><Addroom index={i}/></div>
)}
{!setState({flag}) && (
<div><HomePage index={i}/></div>
)}
</div>
)
}
export default App;
HomePage
import React from 'react'
export default function HomePage() {
return (
<div>
HomePage
</div>
)
}
Addroom
import React from 'react'
export default function Addroom() {
return (
<div>
Addroom
</div>
)
}
I didn't test it but as i can see it should be something like this:
<button onClick={()=>setFlage(true)}>Addroom</button>
<button onClick={()=>setFlage(false)}>HomePage</button>
{flag && (
<div><Addroom index={i}/></div>
)}
{!flag && (
<div><HomePage index={i}/></div>
)}
You need to call setFlage function with argument of Boolean saying true or false and it changes the flag variable that you want to read.
Try the following.
function App() {
const [flag, setFlage] = useState(false);
return (
<div className="App">
<h1>My Smart House</h1>
<button
onClick={() => {
setFlage(true);
}}
>
Addroom
</button>
<button
onClick={() => {
setFlage(false );
}}
>
HomePage
</button>
{flag ? <Addroom /> : <HomePage /> }
</div>
);
}
You are missing render methods and also you should use setState for reactive rendering.( when you use state variables and once value changed render method will rebuild output so this will load your conditinal component.
https://jsfiddle.net/khajaamin/f8hL3ugx/21/
--- HTML
class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div> In Home</div>;
}
}
class Contact extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div> In Contact</div>;
}
}
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
flag: false,
};
}
handleClick() {
this.setState((state) => ({
flag: !state.flag,
}));
console.log("hi", this.state.flag);
}
getSelectedComp() {
if (this.state.flag) {
return <Home></Home>;
}
return <Contact></Contact>;
}
render() {
console.log("refreshed");
return (
<div>
<h1>
Click On button to see Home component loading and reclick to load back
Contact component
</h1
<button onClick={() => this.handleClick()}>Switch Component</button>
{this.getSelectedComp()}
</div>
);
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"));
I've just started learning React and am struggling with conditional rendering. I want to render components based on form input but i'm not sure what needs to be done or where it needs to be executed.
I have imported my Form component which has the input I want to use and have another component like this:
import React, {Component} from 'react';
import Form from './Form';
import CardOne from './CardOne';
import CardTwo from './CardTwo';
import CardThree from './CardThree';
export default class CardContainer extends Component {
render(){
return (
<div>
<CardOne />
<CardTwo />
<CardThree />
</div>
)
}
}
I basically want to be able to show certain Cards if the value of the input is greater than X when the form is submitted, but I don't know how to target an imported component.
This is my Form component:
export default class Form extends Component {
state = {
number: ''
};
change = (e) => {
this.setState({
[e.target.name]: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
this.props.onSubmit(this.state);
this.setState({
number: ''
})
};
render(){
return (
<form>
<label>Number</label>
<input
type="number"
name="number"
placeholder="Number"
value={this.state.number}
onChange={e => this.change(e)} />
<button onClick={e => this.onSubmit(e)}>Submit</button>
</form>
)
}
}
Any help will be massively appreciated!
I have redesigned your Form component , Below is my code. . Let me know if u faced any issues on that .
import React, { Component } from 'react';
import CardOne from './CardOne';
import CardTwo from './CardTwo';
import CardThree from './CardThree';
export default class Form extends Component {
state = {
number: '',
showOne:true,
showTwo:false,
showThree:false,
userInputValue:''
};
change = (e) => {
this.setState({
userInputValue: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
this.props.onSubmit(this.state);
if (this.state.userInputValue > 10 && this.state.userInputValue <20 ){
this.setState({
showTwo: true,
})
}
if (this.state.userInputValue > 20 && this.state.userInputValue < 30) {
this.setState({
showThree: true,
})
}
};
render() {
return (
<div>
<form>
<label>Number</label>
<input
type="number"
name="number"
placeholder="Number"
value={this.state.userInputValue}
onChange={e => this.change(e)} />
<button onClick={e => this.onSubmit(e)}>Submit</button>
</form>
<div>
{this.state.showOne ?
<CardOne />
:
<div></div>
}
{this.state.showTwo ?
<CardTwo />
:
<div></div>
}
{this.state.showThree ?
<CardThree />
:
<div></div>
}
</div>
</div>
)
}
}
// What i wrote above is your base functionality . You reedit the condition depends on ur requirement .
This is what I came up with following your logic of card rendering. I did not change Form coponent but rather worked on the Container
export default class CardContainer extends Component {
constructor(props) {
super(props);
state = {
number: 0,
}
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit=(number)=>{
this.setState({ number: number });
}
render(){
let i=Math.floor(this.state.number/10)
return (
<div>
<Form onSubmit={() => this.onFormSubmit(number)}
[<CardOne />, <CardTwo />, <CardThree/>].slice(0,i).map(card =>
{card}
)
</div>
)
}
}
I would use render prop for this kind of problem. You can research more about render props but basically your CardContainer component will not render those cards component statically as it is. It will return props.children instead.
And then you will have a function (i.e function TestX) that will have a conditional to check what the value of X is. This is the function that will return either , , based on what X is. The function TestX will receive props from CardContainer, including the value of X that is read from the state.
So I will just use CardContainer component with as its child.
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data: 'First Comes First Serves'
}
this.updateState = this.updateState.bind( this );
};
updateState( e ) {
console.log( e );
// console.log( e.target );
this.setState( {data: e} );
}
render() {
return (
<div>
<Content myDataProp = { this.state.data } updateStateProp = { this.updateState }></Content>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<input type="text" value={ this.props.myDataProp } id="id" />
<div>
<button onClick={ this.props.updateStateProp( document.getElementById( 'id' ).value )}>Click</button>
</div>
<h3>{ this.props.myDataProp }</h3>
</div>
);
}
}
export default App;
Error;
Uncaught TypeError: Cannot read property 'value' of null
I'm very new at React.
Here, input value is assigned as 'First come..'(I suppose so), but error appears,
Thanks in advance.
When you are working with React, it is usually best to completely forget about operations that work directly on the DOM like getElementById. They will either not work at all or in unexpected ways.
Instead, have a look at the excellent React forms documentation.
The idiomatic way to do forms in React is to implement the onChange event handler of the input and store the current value in the compoenent's state. Then you can use it access and use it when the user presses the button.
I totally agree with Timo. I have modified the component for you:
class App extends React.Component {
constructor() {
super();
this.state = {
data: 'First Comes First Serves'
}
this.updateState = this.updateState.bind(this);
};
updateState(e) {
this.setState({ data: e.target.value });
}
render() {
return (
<div>
<Content myDataProp={this.state.data} updateStateProp={this.updateState}></Content>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<input type="text" onChange={this.props.updateStateProp} id="id" />
<div>
<button onClick={this.props.updateStateProp}>Click</button>
</div>
<h3>{this.props.myDataProp}</h3>
</div>
);
}
}
export default App;
Let me know if you are able to get it working.