React show element if input has value and hide if empty - reactjs

im trying to show the p element when the input filed has value "the user writes something in input field" and hides when the input is empty
import React, {useState} from 'react'
function textInput() {
const [isOpen, setIsOpen] = useState(false)
return (
<>
<input type="text" onKeyUp={() => setIsOpen(!isOpen)} />
{
isOpen ?
<p>result</p>
: null
}
</>
)
}
export default textInput

Rather than using an isOpen prop, consider maintaining the text in state. Then, if the text is not empty, show the <p> component:
import React, { useState } from "react";
function textInput() {
const [text, setText] = useState("");
return (
<>
<input
type="text"
value={text}
onChange={(e) => {
setText(e.target.value);
}}
/>
{text && <p>result</p>}
</>
);
}
export default textInput;

Please write code like below. It works.
import React, { useState } from "react";
function textInput() {
const [inputText, setInputText] = useState("")
return (
<>
<input type="text" onChange={ (e) => {
setInputText(e.target.value)
}
}/>
{ (inputText !== "") && <p>result: {inputText}</p> }
</>
)
}
export default textInput;

Related

How to update ANTD text input field in React (like getElementById)

I need the equivalent way up updating a simple text input field like so
document.getElementById("myid").value = "sample input"
using React hooks, and the textfield is an Antd control.
Here is the code I have that doesn't work:
import { Input } from "antd"
import { useRef } from "react";
export default function App() {
const inputRef = useRef();
const myfunction = () => {
inputRef.current = "sample input"
}
return (
<div>
<button onClick={myfunction} >populate textbox</button>
<p/>
<Input ref={inputRef} />
</div>
);
}
You can try this code and read a doc for React.
And take a closer look at the attributes of the components that you take in antd;
const [value, setValue] = useState('');
const myfunction = () => {
setValue('Text')
}
return (
<>
<button onClick={myfunction} >populate textbox</button>
<Input value={value}>
</>
)

React function in a component

I am working in React with components, but I am not getting functions working in the Input component.
I have tried searching on component and onChange or onKeyPress but they do not show what I need. Maybe I'm searching wrong? I did get the component Button working, just not Input.
The code for the component is simple.
import React from 'react';
import styles from './Input.module.css';
function Input({inputText}) {
return <input type='number'
placeholder={inputText}
className={styles.input}
/>
}
export default Input;
The full code I want to use for component Input is as follows.
import React, {useState} from 'react';
import styles from './Food.module.css';
import axios from 'axios';
import Nutrients from '../../components/nutrients/Nutrients'
import {ReactComponent as LoadingIcon} from '../../assets/loading.svg'
import Button from "../../components/button/Button";
import Input from "../../components/input/Input";
function Food() {
const [food, setFood] = useState(null);
const [calories, setCalories] = useState('');
const [disabled, setDisabled] = useState(false);
const [error, setError] = useState('');
const [loading, toggleLoading] = useState('');
async function foodData() {
setError('');
toggleLoading('true')
try {
const result = await axios.get(`https://api.spoonacular.com/mealplanner/generate?apiKey=${process.env.REACT_APP_API_KEY}&timeFrame=day&targetCalories=${calories}`);
setFood(result.data);
} catch (error) {
setError('Oops... something went wrong. Please try again.');
console.log('Something went wrong while retrieving the data.', error);
}
toggleLoading(false);
}
function handleChange(e) {
setCalories(e.target.value);
}
function handleKeyPress(e) {
if (e.key === 'Enter') {
if (disabled) {
return;
}
foodData();
setDisabled(true);
}
}
return (
<>
{error && <p className={styles.error}>{error}</p>}
<div>
<section className={styles.food}>
<Input
inputText='Enter caloriessss'
onChange= {handleChange}
onKeyPress={handleKeyPress}
/>
<Button
onClick={() => {
foodData();
setDisabled(true);
}}
buttonText='Click for your daily meals'
/>
</section>
{loading && <LoadingIcon className={styles.loader}/>}
{food && <Nutrients mealsData={food}/>}
</div>
</>
);
}
export default Food;
The thing I want is for the two functions onChange and onKeyPress to work in the Input component.
Anyone has any ideas? I also tried using () and ''.
Because you don't use props onChange and onKeyPress in Input component. Just add it like this:
function Input({ inputText, onChange, onKeyPress }) {
return (
<input
type="number"
placeholder={inputText}
className={styles.input}
onChange={onChange}
onKeyPress={onKeyPress}
/>
);
}
Or shorter way:
function Input({ inputText, ...props }) {
return (
<input
type="number"
placeholder={inputText}
className={styles.input}
{...props}
/>
);
}
React has no way of knowing the onChange and onKeyPress props should be passed to the input inside of your Input component.
You must pass them along explicitly.
// Add them to your destructured props
function Input({inputText, onChange, onKeyPress}) {
return <input type='number'
onChange={onChange} // Pass them to the input
onKeyPress={onKeyPress} // Pass them to the input
placeholder={inputText}
className={styles.input}
/>
}
In the component Input, your return should be: <input></input>
Because JSX needs to closed tags.

Edit/Update input field with React

I'm new to react and I'm trying to edit an input field after I prefilled its value with an object value from my database, so what should I put on onChange if value is value={data.info}? because I cannot type or change the initial value. I've watched a lot of tutorials but this. and props are very confusing to me
import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import useAsync from '../useAsync';
export default function Details() {
const url = 'https://..';
const { index } = useParams();
const { data } = useAsync(url + index);
const [state, setState] = useState(false);
const showForm = () => {
return (
<div>
<form>
<input type="text" value={data.info} onChange={} />
</form>
</div>
)
}
return (
<div className="details" >
{data && <p key={index}>{data.info}</p>}
<button onClick={() => setState({ showForm: true })}>Edit</button>
{state.showForm ? showForm() : null}
</div>
)
}
You can add "default value" to your state. So you can move the data value to your useState(false) so useState(data)
import React, { useState } from "react";
const App = () => {
const [formInput, setFormInput] = useState(""); // You can add your "data" as default value
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>formInput Value {formInput}</h2>
<input
type="text"
value={formInput}
onChange={(e) => setFormInput(e.target.value)} // You need to set the state with the onchange value from the input
/>
</div>
);
};
export default App;
Link to CodeSandbox

how do I save the cursor position when replacing textarea with a regular expression?

how do I save the cursor position when replacing textarea with a regular expression? Now when typing, if there are 2(two) in the text, it is replaced by 3 and the cursor jumps to the end, if there is no 2, it does not jump.
https://codesandbox.io/s/nifty-haze-rb7kp
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [text, setText] = useState("");
useEffect(() => {
setText(text.replace("2", "3"));
}, [text]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<textarea value={text} onChange={e => setText(e.target.value)} />
<br />
{text}
</div>
);
}
You can grab selectionStart from event and use setSelectionRange to set cursor
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [text, setText] = useState("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<textarea
value={text}
onChange={e => {
let target = e.target;
let val = target.value;
const cursor = e.target.selectionStart;
val = val.includes("2") ? val.replace("2", "3") : val;
setText(val);
setTimeout(() => {
target.setSelectionRange(cursor, cursor);
}, 10);
}}
/>
<br />
{text}
</div>
);
}

Is this an example of 2-way databinding in React using Hooks?

I believe it is because it binds the value back to the property inputText but just want to make sure I'm stating this correctly.
import React, { useState } from "react";
const InputElement = () => {
const [inputText, setInputText] = useState("");
return (
<div>
<input
placeholder="Enter Some Text"
onChange={e => {
setInputText(e.target.value);
}}
/>
</div>
);
};
export default InputElement;
This is a good example of 2 way data binding because when you update the state, the UI changes, and when the UI changes, the state changes. Just need to remind you to set the value prop on the <input> element to inputText so that it's a controlled component.
import React, { useState } from "react";
const InputElement = () => {
const [inputText, setInputText] = useState("");
return (
<div>
<input
placeholder="Enter Some Text"
onChange={e => {
setInputText(e.target.value);
}}
value={inputText}
/>
</div>
);
};
export default InputElement;

Resources