How to make Button work on Input (REACT) - reactjs

I would like to have, an Add button. The following is the React.js code that I thought is one way of implement the logic that I want, but unfortunately it's doesn't work.
my getting this Error:
bundle.js:47 Uncaught Error: Cannot find module "./src/index.js"
at webpackMissingModule at Object.<anonymous>
at __webpack_require__
How do I solve this problem?
import React from "react"
import ReactDOM from "react-dom"
import SearchBar from "./components/search_bar"
const API_KEY = "TheRealAPIKeyWouldGoHere"
const App = () => {
handleChange(value){
this.setState({
value: event.target.value
});
}
return ( <div>
<SearchBar onChange={this.handleChange}/>
</div>
)
}
ReactDOM.render(<App />, document.querySelector(".container"))
This is my component. I have assigned Button to input but i can't figure out how to make it work.
import React, { Component } from "react"
class SearchBar extends Component {
constructor(props){
super(props)
this.state = {term: ""}
}
handleChange(evt){
this.props.onChange(value);
}
render () {
return <div>
<button onClick={this.handleChange}>Search</button>
<input ref="inputName" onChange= { event => console.log(event.target.value)} />
</div>
}
}
export default SearchBar

In your component:
import React, { Component } from "react"
class SearchBar extends Component {
constructor(props) {
super(props)
this.state = { term: '' }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({ value: event.target.term })
}
handleSubmit(event) {
console.log(event.target.value)
event.preventDefault()
}
render() {
return (
<div>
<button onClick={this.handleSubmit}>Search</button>
<input
type="text"
value={this.state.term}
onClick={this.handleChange}
/>
</div>
)
}
}
export default SearchBar

Related

TypeError: this.props.changeUser is not a function

I am new in React Js and want to call the parent method from the child method.
There is a class login.jsx when someone clicks on submits button then a method changeUser in FirstPage.jsx should be invoked but when I try the online solution I am getting same error again and again that this.props.changeUser is not a function.
Login.jsx (child class)
import React, { Component } from 'react';
class Login extends Component {
constructor(props){
super(props);
this.state ={
user : null
}
this.onNameChange = this.onNameChange.bind(this);
this.onHandleClick = this.onHandleClick.bind(this);
}
onNameChange = (event)=>{
this.setState({
user:event.target.value
})
}
onHandleClick=(event)=>{
event.preventDefault();
this.props.changeUser("hello");
}
render() {
return (
<form>
<h3>Sign In</h3>
<div>
<label>User Name</label>
<input type="text" name="userId" placeholder="Enter User name" onChange ={this.onNameChange}/>
</div>
<button className="btn btn-primary btn-block" onClick={this.onHandleClick}>Submit</button>
</form>
);
}
}
export default Login;
FirstPage.jsx (parent class)
import React, { Component } from 'react';
import Login from './Login';
class Firstpage extends Component {
constructor(props){
super(props);
this.state=
{
user:null
}
this.changeUser = this.changeUser.bind(this)
}
changeUser =(x)=>{
console.log(x)
}
render() {
return (
<div>
<Login changeUser ={this.changeUser}/>
</div>
);
}
}
export default Firstpage;import React, { Component } from 'react';
import Login from './Login';
class Firstpage extends Component {
constructor(props){
super(props);
this.state=
{
user:null
}
this.changeUser = this.changeUser.bind(this)
}
changeUser =(x)=>{
console.log(x)
}
render() {
return (
<div>
<Login changeUser ={this.changeUser}/>
</div>
);
}
}
export default Firstpage;
I am getting an error that TypeError: this.props.changeUser is not a function
Please help me.
try to avoid using a lambda expression within you class component. Just create a simple member function:
import React, { Component } from 'react';
import Login from './Login';
class Firstpage extends Component {
constructor(props){
super(props);
this.state=
{
user:null
}
this.changeUser = this.changeUser.bind(this)
}
changeUser(x) // Try to declare this as member function
{
console.log(x)
}
render() {
return (
<div>
<Login changeUser ={this.changeUser}/>
</div>
);
}
}
export default Firstpage
You are making a mistake here while binding , inside constructor
//WRONG
this.onNameChange = this.onNameChange.bind(this);
this.onHandleClick = this.onHandleClick.bind(this);
//RIGHT
this.onNameChange = onNameChange.bind(this);
this.onHandleClick = onHandleClick.bind(this);
CODE:
constructor(props){
super(props);
this.state ={
user : null
}
this.onNameChange = onNameChange.bind(this);
this.onHandleClick = onHandleClick.bind(this);
}

Passing data to another after receiving data from call back in react js

I am a beginner in react js so what I want to do it is :
I want to pass the quizData array to another component , data in quizData is set from a callback function which is submitForm function . But when I try to print the prop in another Component(QuizScreen)
it prints 1 as the value console .
Can anybody Please suggest . Am I doing something wrong with the design pattern ?
Thanks in Advance.
import React from 'react';
import logo from './logo.svg';
import './App.css';
import QuizForm from './QuizForm.js'
import QuizScreen from './QuizScreen';
class App extends React.Component{
state = {
isSubmitted : false,
quizData : [],
}
submitForm = (data) =>{
this.setState({isSubmitted : true,
quizData : this.state.quizData.push(data)
})
console.log("Value of quizData is "+ JSON.stringify(this.state.quizData))
}
render() {
return (
<div className="App">
<div className= "container">
{(!this.state.isSubmitted) ? <QuizForm isFormSubmit= {this.submitForm} /> : <QuizScreen details={this.state.quizData}/>}
</div>
</div>
);
}
}
export default App;
import React from 'react'
class QuizScreen extends React.Component {`enter code here`
constructor(props)
{
super(props)
console.log("Props is "+JSON.stringify(props.details))
}
render(){
return(
<div className= "App">
</div>
)
}
}
export default QuizScreen;
import React , {Component} from 'react'
import FileUpload from './FileUpload';
import QuizScreen from './QuizScreen.js'
import './QuizForm.css'
import InputTextField from './InputTextField';
import fields from './Fields.js';
class QuizForm extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
fileData : [],
negativeMarking : 0,
quizName : '',
category :'',
weightage : 0,
quizTime: '',
isSubmitted: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
myfile = (fileUploadData) =>{
console.log("Hello from myfile"+JSON.stringify(fileUploadData));
this.setState({fileData : fileUploadData})
}
handleChange(event) {
console.log("My values are "+event.target.name)
const value = event.target.value;
this.setState({[event.target.name] :value })
}
handleSubmit(event) {
alert('QuizName is '+event.target.quizName.value)
event.preventDefault();
this.setState({isSubmitted : true})
this.props.isFormSubmit(this.state)
}
render() {
return (
<div className="form-style-6">
<h1>Create Quiz</h1>
<form onSubmit={this.handleSubmit}>
{fields.map(form =>{
return(
<InputTextField
type={form.type}
name={form.name}
_handleChange={this.handleChange}
placeholder= {form.placeholder}
key={form.placeholder}
/>
);
} )}
<FileUpload onFileUpload = {this.myfile}/>
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}
export default QuizForm;
You have to refer the current component scope by putting this keyword when you want to access props. Plus, print it on your console by calling it inside a componentDidMount().
import React from 'react';
class QuizScreen extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('Props is ' + JSON.stringify(this.props.details)); //<-- Here you have to put `this` keyword.
}
render() {
return <div className="App"></div>;
}
}
export default QuizScreen;
import React , {Component} from 'react'
import FileUpload from './FileUpload';
import QuizScreen from './QuizScreen.js'
import './QuizForm.css'
import InputTextField from './InputTextField';
import fields from './Fields.js';
class QuizForm extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
fileData : [],
negativeMarking : 0,
quizName : '',
category :'',
weightage : 0,
quizTime: '',
isSubmitted: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
myfile = (fileUploadData) =>{
console.log("Hello from myfile"+JSON.stringify(fileUploadData));
this.setState({fileData : fileUploadData})
}
handleChange(event) {
console.log("My values are "+event.target.name)
const value = event.target.value;
this.setState({[event.target.name] :value })
}
handleSubmit(event) {
alert('QuizName is '+event.target.quizName.value)
event.preventDefault();
this.setState({isSubmitted : true})
this.props.isFormSubmit(this.state)
}
render() {
return (
<div className="form-style-6">
<h1>Create Quiz</h1>
<form onSubmit={this.handleSubmit}>
{fields.map(form =>{
return(
<InputTextField
type={form.type}
name={form.name}
_handleChange={this.handleChange}
placeholder= {form.placeholder}
key={form.placeholder}
/>
);
} )}
<FileUpload onFileUpload = {this.myfile}/>
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}
export default QuizForm;

REACT - Why isnt my Filter Method Working

Im trying to simply create a search and results feature for an app. The value of the input should reflect the components listed in the CardList Array. The filter doesn't seem to update the CardList. I've logged steps along the way and I've come to the conclusion that its the filter I set up. I cant seem to figure out why it wont filter the list.
import React, {Component} from 'react';
import CardList from './CardList';
import {robots} from './robots';
import './index.css';
class App extends Component {
constructor() {
super()
this.state = {
robots: robots,
searchfield: ''
}
}
onSearchChange = (event) => {
this.setState({ searchfield: event.target.value });
}
render() {
const filteredRobots = this.state.robots.filter(robot => {
return robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
});
return (
<div className="appAlign">
<h1 className="appTitle">RoboFriends</h1>
<input
className="searchBox"
type="search"
placeholder="Search Robots"
onChange={this.onSearchChange}
/>
<CardList robots={filteredRobots} />
</div>
);
}
}
export default App;
The error is not caused by the filter function as I have tested it and it works. It most probably lies with the robots data-set. I have slightly modified the filter function here.
import React, { Component } from "react";
import CardList from "./CardList";
import { robots } from "./robots";
class App extends Component {
constructor() {
super();
this.state = {
robots: robots,
searchfield: ""
};
}
onSearchChange = event => {
this.setState({ searchfield: event.target.value });
};
render() {
const filteredRobots = this.state.robots.filter(robot =>
robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
);
return (
<div className="appAlign">
<h1 className="appTitle">RoboFriends</h1>
<input
className="searchBox"
type="search"
placeholder="Search Robots"
onChange={this.onSearchChange}
/>
<CardList robots={filteredRobots} />
</div>
);
}
}
export default App;
I have made a sandbox with your code which has a sample robots data and a Card that renders the filtered data-set. Take a look.

How to create a to-do list in React without ref

I intend to create a to-do list without using ref as in the many examples, but it isn't working.
The expected behavior is that upon entering an entry, it will show up at the top and upon clicking add, it will create an input box for entering an entry. Currently, upon entering the state returns undefined.
The code can be found below or in this sandbox:
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import ToDo from './todo'
class App extends Component {
constructor() {
super();
this.state = {
todos: []
};
}
onChange=(e)=>{
const newToDos = [...this.state.todos]
newToDos.push(e.target.value)
this.setState({
todos: newToDos
})
}
onAdd=(e)=>{
e.preventDefault();
const newtodos=[...this.state.todos]
this.setState({
todos: newtodos.push("")
})
}
render() {
console.log(this.state.todos)
return (
<div>
<p>All the to-dos include {this.state.todos}</p>
<ToDo
todos={this.state.todos}
/>
<form onSubmit={this.onChange}>
<input
type="text"
placeholder="add a new todo..."
/>
</form>
<button onClick={this.onAdd}>+</button>
</div>
);
}
}
render(<App />, document.getElementById('root'));
And here is the todo.js:
import React, { Component } from 'react';
import { render } from 'react-dom';
export default class ToDo extends Component {
constructor(props){
super(props)
}
render() {
const {todos, onChange}=this.props
return (
<div>
{
todos.map((todo, index)=>
<div>
{todo}
</div>
)
}
</div>
);
}
}
You can store your new todo in state when onChange input and add this into todos when click save.
I have forked and edit your sample.
https://stackblitz.com/edit/react-nwtp5g?file=index.js
BTW: In your sample, newtodos.push("") will return the length of newtodos array, not the array after pushed.
onAdd=(e)=>{
e.preventDefault();
const newtodos=[...this.state.todos]
this.setState({
todos: newtodos.push("")
})
Hope this help.
your code newtodos.push("") dosent return array so no map function:
this.setState({
todos: newtodos.push("")
})
correct it something like this
this.setState({
todos: newtodos.concat("new value")
})
You have a problem with this code,
<form onSubmit={this.onChange}>
<input
type="text"
placeholder="add a new todo..."
/>
</form>
Here you are adding onSubmit on form, which will never call because you don't have submit button.
you should do something like this,
<form>
<input
type="text"
placeholder="add a new todo..."
onChange={this.onChange}
value={this.state.currentValue}
/>
</form>
onChange=(e)=>{
event.preventDefault();
this.setState({
currentValue: e.target.value
})
}
onAdd=(e)=>{
e.preventDefault();
const newToDos = [...this.state.todos]
newToDos.push(this.state.currentValue)
this.setState({
todos: newToDos,
currentValue: ''
})
}
Demo
Update
In your todo component you have useless constructor, If you don't have state in a component or don't have any function to bind this don't add constructor.
You can remove the constructor.
Another thing is, you are not passing any onChange prop to todo component, so here you will get undefined for onChange.
const {todos, onChange}=this.props
You can also write this component as a functional component.
You can update your code with
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import ToDo from './todo'
class App extends Component {
constructor() {
super();
this.state = {
todos: [],
inputText: ""
};
}
onAdd= () => {
this.setState({
todos: [...this.state.todos, this.state.inputText], textInput: ""
})
}
render() {
console.log(this.state.todos)
return (
<div>
<p>All the to-dos include {this.state.todos}</p>
<ToDo
todos={this.state.todos}
/>
<form>
<input
type="text"
placeholder="add a new todo..."
onChange={inputText => this.setState({inputText})}
/>
</form>
<button onClick={this.onAdd}>+</button>
</div>
);
}
}
render(<App />, document.getElementById('root'));
And in todo.js you can simply do
import React, { Component } from 'react';
import { render } from 'react-dom';
export default const ToDo = ({todos}) => {
return(<div>
{todos.map((todo, index) => (
<div key={index}>
{todo}
</div>))}
</div>)}
as it do not contains any state associated with it.

this.props.createTask is not defined

I am following this tutorial React Tutorial
Here is the thing:
I am calling function createTask from create-todo.js;
the function is defined in app.js
app.js
import React from 'react';
import ToDosList from './todos-list';
import CreateToDoItem from './create-todo-item'
const todoitems=[
{
task: 'finish react todo tutorial',
isCompleted: false
},
{
task: 'eat lunch',
isCompleted: true
}
];
export default class App extends React.Component
{
constructor(props){
super(props)
this.state={
todoitems
};
}
render()
{
return(
<div>
<h1>React Demo App - ToDos </h1>
<CreateToDoItem createtask ={this.createTask.bind(this)}/>
<ToDosList
todoitems={this.state.todoitems}
/>
</div>
);
}
createTask(task)
{
//alert('called');
this.state.todoitems.push({
task,
isCompleted:false
});
this.setState({todoitems: this.state.todoitems});
}
}
create-todo.js
import React from 'react';
import App from './app';
export default class CreateToDoItem extends React.Component
{
render()
{
return(
<form onSubmit={this.handleCreate.bind(this)}>
<input type="text" placeholder="what do I need to do?" ref="createInput"/>
<button>Create</button>
</form>
);
}
handleCreate(event)
{
event.preventDefault();
//alert('called');
this.props.createTask(this.refs.createInput.value); //this throws error
}
}
I am absolutely new to React.js. I don't know how this works. Should the function be available to create-todo.js? The code is exactly how it is shown in the tutorial.
Reason is, you are passing the function in props by a different key and using inside child by a different key.
Actual function name: createTask
Passing in props by key: createtask
Using inside child by: createTask
so use this.props.createtask() instead of this.props.createTask()
Your prop is named "createtask". You should probably change your prop name to createTask (as opposed to changing references to this.props.createtask).
You could do like this:
import React from 'react';
import ToDosList from './todos-list';
import CreateToDoItem from './create-todo-item'
const items = [
{
task: 'finish react todo tutorial',
isCompleted: false
},
{
task: 'eat lunch',
isCompleted: true
}
];
export default class App extends React.Component {
state = {
todoitems: items,
taskItem: ''
}
handleChange = (e) => {
this.setState({
taskItem: e.target.value
})
}
handleCreate = () => {
e.preventDefault()
item = {
task: taskItem,
isCompleted: false // default value
}
this.setState({
todoitems: [...this.state.todoitems, item ]
})
}
render() {
return (
<div>
<h1>React Demo App - ToDos </h1>
<CreateToDoItem
handleChange={this.handleChange}
handleCreate={this.handleCreate}
taskItem={this.state.taskItem}
/>
<ToDosList todoitems={this.state.todoitems}
/>
</div>
);
}
}
Then your form will be:
import React from 'react';
import App from './app';
export const CreateToDoItem = (props) => (
<form onSubmit={props.handleCreate}>
<input type="text" placeholder="what do I need to do?"
onChange={props.handleChange}
value={props.taskItem} />
<button type='submit'>Create</button>
</form>
);
I hope it help you :)
Kindly,

Resources