Get value of input text with react-bootstrap - javascript

I try to get value into a input text and add it to a text area with react-bootstrap.
I know I must use ReactDOM.findDOMNode to get value with ref. I don't understand what is wrong.
Here my code :
import React from 'react';
import logo from './logo.svg';
import ReactDOM from 'react-dom';
import { InputGroup, FormGroup, FormControl, Button} from 'react-bootstrap';
import './App.css';
class InputMessages extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.GetMessage= this.GetMessage.bind(this);
this.state = {message: ''};
}
handleChange(event)
{
this.setState({message: this.GetMessage.value});
}
GetMessage()
{
return ReactDOM.findDOMNode(this.refs.message );
}
render() {
var message = this.state.message;
return(
<FormGroup >
<FormControl
componentClass="textarea" value={message} />
<InputGroup>
<FormControl type="text" ref='message' />
<InputGroup.Button>
<Button bsStyle="primary" onClick={this.handleChange}>Send
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
);
}
}
export default InputMessages;

Form Control has a ref prop, which allows us to use React Refs
Sample Code :
class MyComponent extends React.Component {
constructor() {
/* 1. Initialize Ref */
this.textInput = React.createRef();
}
handleChange() {
/* 3. Get Ref Value here (or anywhere in the code!) */
const value = this.textInput.current.value;
}
render() {
/* 2. Attach Ref to FormControl component */
return (
<div>
<FormControl ref={this.textInput} type="text" onChange={() => this.handleChange()} />
</div>
)
}
}
Hope this helps!

Add an Input ref to your form :
<FormControl inputRef={ref => { this.myInput = ref; }} />
so now you get the value like
this.myInput.value

Related

getting material-ui TextField value onsubmit

I want to get the value of TextField input and render the message conditionally. I tried this one, its working but this one is functioning dynamically because I used onChange. I want to achieve the same but using onSubmit on <Button> Is there anyway to do that?
import React from 'react';
import { Component } from 'react';
import Button from '#mui/material/Button';
import { TextField } from '#mui/material';
class App extends Component
{
state = {
myValue: null,
}
handleChange = (e) => this.setState({
myValue: e.target.value
})
render() {
return (
<div>
<TextField
value={this.state.myValue}
onSubmit={this.handleChange}
/>
<button >Get Weather</button>
{this.state.myValue ? <p>value inputed </p>: <p>no input</p>}
</div>
)
}
}
export default App;
Using Refs is what you need. You can get the current value of your input by clicking a button and only then change the state.
Demo
import React, { createRef } from "react";
import { Component } from "react";
import { TextField } from "#mui/material";
class App extends Component {
constructor(props) {
super(props);
this.textInput = createRef();
this.state = {
myValue: ""
};
}
showRefContent = () => {
this.setState({
myValue: this.textInput.current.value
});
};
handleChange = (e) =>
this.setState({
myValue: e.target.value
});
render() {
return (
<div>
<TextField inputRef={this.textInput} />
<button onClick={this.showRefContent}>Get Weather</button>
<p>
{this.state.myValue.length > 0
? `text:${this.state.myValue}`
: "no text"}
</p>
</div>
);
}
}
export default App;
you just need to you onkeydown instead onsubmit.
<TextField
value={this.state.myValue}
onKeyDown={this.handleChange}
/>
or use
<form onSubmit={handleChange }>
<TextField
value={this.state.myValue}
onKeyDown={this.handleChange}
/>
<button type="submit">submit</button>
</form>

Input tag onChange returning undefine value

I have been stuck on one issue to fetch the input text field from the input field. Essentially, I want to make a search function that gets the text and processes it further.
Please refer to the code for the information and returning div is at the bottom.
import React from 'react';
import ReactDOM from 'react-dom';
import { useState, useEffect } from 'react';
import { Input, InputGroup, Icon} from 'rsuite';
import { Button, IconButton, ButtonGroup, ButtonToolbar } from 'rsuite';
import './App.css';
import Search from './search.js';
// import default style
import 'rsuite/dist/styles/rsuite-default.css';
import { render } from 'react-dom';
const styles = {
marginBottom: 10
};
const center = {
padding: '25% 25% 25%'
}
class App extends React.Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
inputValue: 'Nothing'
}
}
handleInputChange(event){;
this.setState({inputValue: event.target.value});
};
render(){
return (
<div >
<div style={center} >
<InputGroup style={styles}> <Input size="md" value={this.inputValue} onChange={(e) => this.handleInputChange(e)} /><InputGroup.Addon>
<Button appearance="default"><Icon icon="search" /></Button>
</InputGroup.Addon>
</InputGroup>
</div>
</div>
)
}
}
export default App;
There's a ; in the start of your handleInputChange function.
Input from rsuite directly returns value onChange but you are referring to e.target.value.
And also the value should be this.state.inputValue
Here is the solution.
handleInputChange(value) {
console.log("values>>>>", value);
this.setState({ inputValue: value });
}
render() {
return (
<div>
<div style={center}>
<InputGroup style={styles}>
{" "}
<Input
size="md"
value={this.state.inputValue}
onChange={(e) => this.handleInputChange(e)}
/>
<InputGroup.Addon>
<Button appearance="default">
<Icon icon="search" />
</Button>
</InputGroup.Addon>
</InputGroup>
</div>
</div>
);
}
}
you can also refer to https://codesandbox.io/s/zen-field-njxn0?file=/src/App.js:590-1213
Your problem is very simple. You are setting value={this.inputValue} but you should use value={this.state.inputValue}. Because this.inputValue doesn't exist, your value gets set to undefined. Using value={this.state.inputValue} should fix your problem.

How to get the whole block of data using reactjs?

I've created a component which displays only block[0] value, it is not showing the whole block value.
For Example, if I write :
HI
Stackoverflow
It is showing only "Hi", It's not showing the full content of the field.
Can anyone help me in getting the whole data whatever I write in that input field?
import React from "react";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
export default class Edit extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<Editor value={this.props.value} onChange={this.props.onChange} />
</div>
);
}
}
App component:
import React from "react";
import Body from "./Body";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
body: ""
};
}
changeBodyHandler = value => {
console.log(value.blocks[0].text);
this.setState({
body: value.blocks[0].text
});
};
render() {
return (
<div>
<Body
label="Body"
name="body"
value={this.state.body}
onChange={this.changeBodyHandler}
/>
</div>
);
}
}
export default App;
Here is the whole code:
"https://codesandbox.io/s/compassionate-tereshkova-89fm2"
Can anyone please help me with this?
Each line to list, then map(), join() with \n would be fine
this.setState({ body: value.blocks.map(x => x.text).join("\n") });
import React from "react";
import Body from "./Body";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
body: ""
};
}
changeBodyHandler = value => {
this.setState({ body: value.blocks.map(x => x.text).join("\n") });
};
render() {
console.log(this.state.body);
return (
<div>
<Body
label="Body"
name="body"
value={this.state.body}
onChange={this.changeBodyHandler}
/>
</div>
);
}
}
export default App;
Try it online:
If you want with break line like as it is in editor, add <p> tag while concatination.
changeBodyHandler = value => {
let data =value.block;
let text = "";
data.map(index => {
text = text +"<p>" +index.text+"</p>";
});
this.setState({
body: text
});
};
And if you want to display the data in same way somewher use dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{__html: this.state.body}} />

Why doesn't this grab the text from my input? error?

Currently very new to React. Trying to make a input box and when I type into the input box and click submit, an alert box pops up with the text that I typed.
import React from "react";
import "./App.css";
class TodoListt extends React.Component {
state = {};
constructor(props) {
super(props);
this.input = React.createRef();
}
handleSubmit(e) {
e.preventDefault();
console.log(this._inputElement.value);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input ref={a => (this._inputElement = a)} placeholder="...todo" />
<button>submit</button>
</form>
</div>
);
}
}
export default TodoListt;
TypeError: Cannot read property '_inputElement' of undefined
Change handleSubmit to an arrow function:
handleSubmit = (e) => {
e.preventDefault();
console.log(this._inputElement.value);
}
This is an excellent article on the subject.
Try this:
import React from "react";
import "./App.css";
class TodoListt extends React.Component {
state = {};
constructor(props) {
super(props);
this.input = React.createRef();
}
handleSubmit(e) {
e.preventDefault();
console.log(this.input.current.value);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input ref={this.input} placeholder="...todo" />
<button>submit</button>
</form>
</div>
);
}
}
export default TodoListt;

Type is invalid -- expected a string

I am building a Meteor app with ReactJS and Semantic-UI for react. I have run into a problem when trying to create a form for a new item that appears as a modal. I receive the following error.
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `App`.
App.jsx file:
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Items } from '../api/items.js';
import { Item } from './Item.jsx';
import { ItemFormModal } from './ItemFormModal.jsx';
// App component - represents the whole app
export class App extends Component {
renderItems() {
return this.props.items.map((item) => (
<Item key={item._id} item={item} />
));
}
render() {
return (
<div className="container">
<header>
<h1>Products</h1>
<ItemFormModal />
</header>
<ul className="collection">
{this.renderItems()}
</ul>
</div>
);
}
}
App.propTypes = {
items: PropTypes.array.isRequired,
};
// creates container on client side for the collection
export default createContainer(() => {
return {
// fetch all the items available
items: Items.find({}, { sort: { createdAt: -1 } }).fetch(),
};
}, App);
EDIT: I have changed it to reflect the whole ItemFormModal.jsx:
import { Items } from '../api/items.js';
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
// Import all semantic resources
import { Button, Icon, Header, Form, Modal } from 'semantic-ui-react';
export default class ItemFormModal extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "",
price: 0.00,
modalOpen: false
}
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleOpen(event) { this.setState({ modalOpen: true }) }
handleClose(event) { this.setState({ modalOpen: false }) }
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
let title = this.state.title.trim();
let price = this.state.price;
Items.insert({
title: title,
price: price,
recurring: false,
createdAt: new Date(), // current time
});
this.setState({
title: "",
price: 0.00
});
}
render() {
return (
<div id="new-item">
<Button onClick={this.handleOpen}>Create</Button>
<Modal
open={this.state.modalOpen}
onClose={this.handleClose}
size="small"
closeIcon="close">
<Modal.Header>Create new item</Modal.Header>
<Modal.Content>
<Form>
<Form.Group>
<Form.Input name="title" label="Title" placeholder="Title" value={this.state.title} onChange={this.handleInputChange}/>
<Form.Input name="price" label="Price" placeholder="Price" value={this.state.price} onChange={this.handleInputChange} />
</Form.Group>
</Form>
</Modal.Content>
<Modal.Actions>
<Button className="negative" onClick={this.handleClose}>Cancel</Button>
<Button className="positive" onClick={this.handleSubmit}>Create</Button>
</Modal.Actions>
</Modal>
</div>
)
}
}
Any help is greatly appreciated!
you are importing into App.jsx incorrectly. you have this:
import { ItemFormModal } from './ItemFormModal.jsx';
... which will not work if your export is marked as default. you can either remove "default" from your export, or you can change your import to this:
import ItemFormModal from './ItemFormModal.jsx';

Categories

Resources