pass input data from one component to another component in react js? - reactjs

I am new to learning React.
I wanted to make it: when entering data into the input, this data automatically appear in H1in another component.
Screen.js
class Screen extends React.Component {
render() {
return (
<div className="screen">
<h1>Text from input</h1>
</div>
);
}
}
export default Screen;
Inputs.js
class Inputs extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Value: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Enter" />
</form>
);
}
}
export default Inputs;
App.js
export default function App() {
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<Inputs />
<Screen />
</div>
);
}

You have to lift the state up to the app.js.
export default function App() {
const [val, setVal] = useState('');
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<Inputs val={val} setVal={setVal} />
<Screen val={val}/>
</div>
);
}
Your inputs.js
export default const Inputs({val, setVal}) => {
const handleChange => (event) {
this.setState({value: event.target.value});
};
const handleSubmit => (event) {
alert('Value: ' + this.state.value);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={val} onChange={handleChange} />
<input type="submit" value="Enter" />
</form>
);
}
}
export default Inputs;
Your screen.js
export default const Screen({val}) => {
return (
<div className="screen">
<h1>{val}</h1>
</div>
);
}
```

write your app.js code as
export default function App() {
const [input,setInput] = useState('')
const setInputValue = (value) => {
setInput(value)
}
return (
{Hello StackBlitz!${input}}
Start editing to see some magic happen :)
);
}
and inside your handleChange function write props.setInputValue(event.target.value)
and use input props in Screen.js file as props.input

Related

How can I take a input from user and change it with setState?

constructor() {
super();
this.state = {
name: "",
name1: "",
};
}
change = () => {
this.setState({ name: this.state.name1 });
};
handleChange = (e) => {
this.setState({ name1: e.target.value });
};
render() {
return (
<div>
<input
type="text"
placeholder="Enter your name"
onChange={this.handleChange}
></input>
<button onClick={this.change}>Click Me!</button>
<h4>Hello! {this.state.name}</h4>
</div>
);
}
This is what I did but feels like it is nonsense on actual webpage even it works. Is there a better way to take input from user?
Why you need name and name1 in state. Just name should be fine. See the below code if that helps
I am not sure why you handle a event in button. May you can use a form with OnSubmit.
import React from "react";
import "./style.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
name: "",
};
}
render() {
return (
<div>
<input
type="text"
placeholder="Enter your name"
onChange={(e) => this.setState({name: e.target.value})}
/>
<button>Click Me!</button>
<h4>Hello! {this.state.name}</h4>
</div>
);
}
}
Your onChange in the input would be
onChange={event => this.handleChange(event)}
And for the button it would be
onChange{() => this.change()}
We would not require 2 states for the name but we would need one variable to store the name and second variable to let the component know that name has been update. We need the second variable because on button click only the name has to be updated(as per the code mentioned).The component would re-render when a state is updated. Below code might be helpful.
class Content extends React.Component {
constructor(){
super()
this.state = {
name: "",
}
this.name=''
}
change = () => {
this.setState({name: this.name})
}
handleChange = (e) => {
this.name=e.target.value
}
render(){
return(
<div>
<input type = "text" placeholder="Enter your name" onChange={this.handleChange}></input>
<button onClick={this.change}>Click Me!</button>
<h4>Hello! {this.state.name}</h4>
</div>
)
}}
Here is a version with React Hooks:
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const handleNameChange = (e) => {
const nameInput = e.target.value;
setName(nameInput);
};
return (
<div>
<input
type="text"
placeholder="Enter your name"
onChange={(e) => handleNameChange(e)}
></input>
<button>Click Me!</button>
<h4>Hello! {name}</h4>
</div>
);
}

Passing Event from Parent to Child-Child

I would like to know how to accomplish this.
Passing an event from Parent to Child/Child, by this example: I have Apps.js, then FormDynamic.js and two Inputs. I want to pass handleChange from the Apps.js to FormDynamic.js and then to InputTextField.js and get the value from the App.js on the submitForm function.
//Apps.js
import React, {Component} from 'react';
import FormDynamic from './components/FormDynamic'
class App extends Component {
constructor(props)
{
super(props);
this.state={
fields: [
{id:"101", name:"101", placeholder:"Enter Value 1",input_type:"text",required:true},
{id:"102", name:"102", placeholder:"Enter Value 2",input_type:"number",required:true}
]
}
this._handleChange = this._handleChange.bind(this);
}
_handleChange = event =>{
this.setState({
[event.currentTarget.id]: event.currentTarget.value
});
};
submitForm = event =>{
const {fields, ...inputFields} = this.state;
console.log(fields);
console.log(inputFields);
event.preventDefault();
};
render(){
return (
<div className="App">
<FormDynamic fields={this.state.fields} handleChange={this._handleChange} />
<button onClick={this.submitForm}>Enviar Datos</button>
</div>
);
}
}
export default App;
//FormDynamic.js
import React, {Component} from 'react';
import InputTextField from './InputTextField'
import InputNumberField from './InputNumberField'
class FormDynamic extends Component
{
constructor(props)
{
super(props);
}
render()
{
return(
<div>
{this.props.fields.map(form => {
if (form.input_type ==="text")
{
return (
<InputTextField
id={form.id}
name={form.name}
placeholder={form.placeholder}
required={form.required}
key={form.id}
onChange = {this.props.handleChange}
/>
);
}
if (form.input_type ==="number")
{
return (
<InputNumberField
id={form.id}
name={form.name}
placeholder={form.placeholder}
required={form.required}
key={form.id}
onChange = {this.props.handleChange}
/>
);
}
return null;
})}
</div>
)
};
}
export default FormDynamic;
//InputTextField.js
import React from 'react';
const InputTextField = ({id,name,placeholder,required,_handleChange}) =>
(
<div>
<input type="text"
id={id}
name={name}
required={required}
placeholder={placeholder}
onChange={_handleChange}
/>
</div>
);
export default InputTextField;
From FormDynamic.js your passing props onChange to InputTextField.js but your reading wrong props _handleChange instead read onChange props, try the below code it will work.
//InputTextField.js
import React from 'react'
const InputTextField = ({id, name, placeholder, required, onChange}) => (
<div>
<input type="text"
id={id}
name={name}
required={required}
placeholder={placeholder}
onChange={onChange}
/>
</div>
)
export default InputTextField

Screen disappears on inserting any text in Input field

When I insert any text in input field, screen disappears, I am new to UI, learning ReactJs, help me out please.
import React from 'react';
class InputChange extends React.Component{
constructor(props){
super(props)
this.state={
input:''
}
}
updateState = (text) => {
this.setState({input: text});
}
render(){
return(
<div>
<div>Input:{this.state.input}</div>
<div>
<input type="text" value={this.state.input} onChange={this.updateState} />
</div>
</div>`
);
}
}
export default InputChange;
It's event.target.value...:
class InputChange extends React.Component {
state = { input: '' };
updateState = event => {
this.setState({ input: event.target.value });
};
render() {
return (
<div>
<div>Input:{this.state.input}</div>
<div>
<input
type="text"
value={this.state.input}
onChange={this.updateState}
/>
</div>
</div>
);
}
}
export default InputChange;
More info in the docs: https://reactjs.org/docs/forms.html

react-router - how change the url

I need to have the user edit the url the "path" appears in the input of the other component and when searching the input change the url in real time. How can I use "withRouter" to perform this function?
// App.js component
class App extends Component {
render() {
const { match, location, history } = this.props;
return (
<div >
<Search
searchString={location.pathname}
/>
</div>
)
}
}
export default withRouter(App)
//Search.js component
const Search = ({ searchString }) => (
<div>
<input
value={searchString}
type="search"
placeholder="Search"
aria-label="Search"
/>
</div>
)
This should work for you although I'm not sure redirecting user to another page while typing into search input is a good UX.
// App.js component
class App extends Component {
state = {
searchString: this.props.location.pathname
}
handleSearch = (event) => {
this.setState(
{ searchString: event.target.value },
() => this.props.history.push('/search?query=' + this.state.searchString)
);
}
render() {
return (
<div >
<Search
onChange={this.handleSearch}
searchString={this.state.searchString}
/>
</div>
)
}
}
export default withRouter(App)
const Search = ({ searchString, onChange }) => (
<div>
<input
onChange={onChange}
value={searchString}
type="search"
placeholder="Search"
aria-label="Search"
/>
</div>
)

How to log data from input onto the console in React

I would like to know how to have it where when I press enter on my keyboard, it logs whatever is in the input onto the console. Please help. Thanks!
import React, { Component } from 'react';
import './App.css';
class App extends Component {
onClick() {
alert("CLICKED");
}
onChange(eve) {
console.log(eve.target.value);
}
onSubmit() {
alert("SUBMITTED");
}
render() {
const list = ["Lebron", "Kobe", "Steph", "Kevin"];
return (
<div className="App">
<h1>{
list.map(listitem =>{
return (
<div onClick={this.onClick}>
{listitem}
</div>
)})
}</h1>
<form onSubmit={this.onSubmit}>
<input onChange={this.onChange} />
</form>
</div>
);
}}
export default App;
Please help!
Store the input value in a state variable onChange and then log it to the console onSubmit.
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
onChange = event => {
this.setState({ value: event.target.value});
}
onSubmit = event => {
const { value } = this.state;
event.preventDefault();
console.log(value);
}
render() {
const list = ["Lebron", "Kobe", "Steph", "Kevin"];
const { value } = this.state;
return (
<div className="App">
...
<form onSubmit={this.onSubmit}>
<input onChange={this.onChange} value={value}/>
</form>
</div>
);
}
}

Resources