I have a problem I can not solve myself in relation to react.
What I am trying to do is add props to my Component
So I can use my compnent again and again just with a string relative to a variable so I can just write e.g.
I really searched for some different things but none that worked.
Just hoping you can get me on.
Hope it makes sense otherwise feel free to ask
My Component
import React, { Component } from "react";
export default class UserSelections extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
// ComponentDidMount is used to
// execute the code
componentDidMount() {
fetch(
"URL")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Vent et øjeblik... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1>
<form onSubmit={this.handleSubmit}>
<label><select name={this.state.slug} value={this.state.value} onChange={this.handleChange}>
{ --->Need Variable here<--- Down here
items.filter(slug => slug.slug === **'bygnings-st'**).map((item, index) => (
<option value={ item.outputvalue } key={index}>{ item.outputvalue }</option>
))
}</select>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
import React from "react";
import UserSelections from "./components/UserSelections";
import './App.css';
function App() {
return (
<div className="App">
<UserSelections **Need props here** /> <-------------------
</div>
);
}
export default App;
Best regards
Morten
If you want to pass a string as prop:
const value = "hi";
<UserSelections stringProp={value} />
And you display the value with:
{this.props.stringProp}
inside of the UserSelections component
Related
I'm currently working on a project that uses QuillJS for a rich text editor. I need to post the rich text content to my backend but I'm not sure how to access the QuillJS output.
In RichTextEditor.js
import React, { Component } from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
class RichTextEditor extends Component {
constructor(props) {
super(props);
// this.formats = formats;
this.state = { text: "" }; // You can also pass a Quill Delta here
this.handleChange = this.handleChange.bind(this);
}
handleChange(value) {
this.setState({ text: value });
const text = this.state;
console.log(text);
}
render() {
return (
<ReactQuill
value={this.state.text}
onChange={this.handleChange}
formats={this.formats}
modules={this.modules}
/>
);
}
}
export default RichTextEditor;
The console.log(text) basically just outputs the content of the rich text editor. Something like this "<p><em>aasdasdasd</em><strong><em>asdasdasdasd</em></strong></p>"
In Post.js
import React, { Component } from "react";
import RichTextEditor from "./RichTextEditor.js";
import "../../css/Post.css";
class Post extends Component {
constructor(props) {
super(props);
this.state = {
question: "",
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state);
};
handleSubmit = (e) => {
e.preventDefault();
const { question } = this.state;
console.log("Question");
console.log(question);
render() {
const { question } = this.state;
return (
<div className="post">
<div className="post__container">
<form onSubmit={this.handleSubmit}>
<div className="post__richTextEditor">
<RichTextEditor value={question} onChange={this.onChange} name="question" />
</div>
</form>
</div>
</div>
);
}
}
export default Post;
I'm trying to update the state of the question but it doesn't seem to be updating. console.log(question) only outputs a single string.
How can I access the same string output from RichTextEditor.js?
Your RichTextEditor component should not handle change, it should only receive props from higher component:
class RichTextEditor extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ReactQuill
value={this.props.value}
onChange={this.props.onChange}
formats={this.formats}
modules={this.modules}
/>
);
}
}
export default RichTextEditor;
Then your Post component pass value and onChange props to RichTextEditor:
class Post extends Component {
constructor(props) {
super(props);
this.state = {
question: "",
};
this.onChange = this.onChange.bind(this);
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state);
};
handleSubmit = (e) => {
e.preventDefault();
const { question } = this.state;
console.log("Question");
console.log(question);
render() {
const { question } = this.state;
return (
<div className="post">
<div className="post__container">
<form onSubmit={this.handleSubmit}>
<div className="post__richTextEditor">
<RichTextEditor value={question} onChange={this.onChange} name="question" />
</div>
</form>
</div>
</div>
);
}
}
in RichTextEditor.js
handleChange(value) {
this.setState({ text: value });
const text = this.state;
console.log(text);
props.onChange(text); // passing the inner State to parent as argument to onChange handler
}
Now in Post.js
onChange = (newStateString) => {
//this.setState({ [e.target.name]: e.target.value });
console.log(newStateString); // you should get the string here
};
started learning react. I've been sitting on this problem for an hour and I have no idea why this is not working. Looking everywhere, but without any results. Am I dumb or what?
I cannot write in input field or when I can (if I fix it) then my state doesn't change. Maybe someone knows why is that a problem?
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
text: "test"
}
}
textChangedHandler = (event) => {
this.setState = ({
text: event.target.value
});
}
render() {
return (
<div className="App">
<p>{this.state.text}</p>
<input
type="text"
onChange={this.textChangedHandler}
value={this.state.text}>
</input>
</div>
);
}
}
export default App;
see your textChangedHandler
textChangedHandler = (event) => {
this.setState = ({
text: event.target.value
});
}
In this,
you need to set state like this.
this.setState({
text: event.target.value
})
this.setState is a method. You should need to reassign it.
textChangedHandler = (event) => {
this.setState({
text: event.target.value
});
}
render() {
return (
<div className="App">
<p>{this.state.text}</p>
<input
type="text"
onChange={this.textChangedHandler}
value={this.state.text}>
</input>
</div>
);
}
try this.
Try this one:
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
text: "test"
}
// This binding is necessary to make `this` work in the callback
this.textChangedHandler = this.textChangedHandler.bind(this)
}
textChangedHandler = (event) => {
this.setState({
text: event.target.value
});
}
render() {
return (
<div className="App">
<p>{this.state.text}</p>
<input
type="text"
onChange={this.textChangedHandler}
value={this.state.text}>
</input>
</div>
);
}
}
export default App;
More information: https://reactjs.org/docs/handling-events.html
Here is my simple to-do app program where I have made only one component which takes in the input form user and passes that input value to App.js to update items in App.js state.
todo-form.component.js
import React from 'react';
class SignInForm extends React.Component {
constructor(){
super();
this.state ={
temp: null
};
}
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value
},
console.log(this.state)
);
// this.props.addInput(e.target.value);
}
handleSubmit= (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
}
render(){
return(
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;
App.js
import React from 'react';
import './App.css';
import SignInForm from './components/todo-form/todo-form.component'
import ItemList from './components/todo-list/todo-list.component';
class App extends React.Component {
constructor(){
super();
this.state = {
input: []
};
}
addInput = (item) => {
let newInput=[...this.state.input,item];
console.log(newInput);
this.setState = ({
input: newInput
},
console.log(this.state)
);
}
render(){
return (
<div className="App">
<h1>TO-DO LIST</h1>
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
On taking input the state inside todo-form.component.js is getting updated with the typed input value but on passing state.temp in handleChange function, the state inside App.js is not updating when addInput function is called.
Please help me on this issue and how my state is not getting updated in App.js??
Your setState is the problem. Have a look at my code.
App.js
class App extends React.Component {
state = {
input: [],
};
addInput = (item) => {
let newInput = [...this.state.input, item];
//setState should be this way
this.setState({
input: newInput,
});
};
render() {
return (
<div className="App">
<h1>TO-DO LIST</h1>
{this.state.input.map((el) => (
<li> {el}</li>
))}
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
Login file.
class SignInForm extends React.Component {
// constructor(props) {
// super(props);
state = {
temp: null,
};
// }
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value,
});
// this.props.addInput(e.target.value);
};
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
};
render() {
return (
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;
I render a form and a list. It works just fine at the initial load up:
<UsersList
users={this.state.users}
/>
<SendMessageForm
sendMessage={this.addMessage}
/>
However, when the SendMessageForm is submitted this.state.users loses its value and I get the error of Cannot read property 'map' of undefined.
Here is the SendMessageForm:
export default class SendMessageForm extends React.Component {
constructor() {
super();
this.state = {
message: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
message: e.target.value
});
}
handleSubmit(e) {
e.preventDefault();
this.props.sendMessage(this.state.message);
this.setState({
message: ''
});
}
render() {
return (
<div id="MessageField">
<form
onSubmit={this.handleSubmit}
className="send-message-form">
<input
onChange={this.handleChange}
value={this.state.message}
placeholder="Type your message and hit ENTER"
type="text"
/>
</form>
</div>
);
}
}
Here is the UserList:
import React, { Component } from 'react';
class UsersList extends Component {
render() {
return (
<div id="UList">
<ul className="users-list">
{this.props.users.map((user, index) => {
return (
<li key={index}>
<span>{user}</span>
</li>
);
})}
</ul>
</div>
);
}
}
export default UsersList;
Could you help me understand how the state variable users loses its value?
EDIT:
Adds message to the MessageList. MessageList works just fine, the problem is with the UsersList. By the way I am using Chatkit library.
addMessage(text) {
this.state.currentUser.sendMessage({
text,
roomId: this.state.roomId.toString()
})
.catch(error => console.error('error', error));
}
I am new to react and having hard time figuring on how to show up the value from another component to the edit file component. Basically, I am able to create a message using draft.js rich text editor and able to save it to the database in the backend. Now I need to work on the update/edit part. How do I get the description state value to show up in the rich text editor? Can anyone please help?
Create File
import { EditorState } from 'draft-js';
class CreateModal extends Component {
constructor(props) {
super(props);
this.state = {
description: EditorState.createEmpty()
};
this.handleEditorState = this.handleEditorState.bind(this);
}
handleEditorState(editorState) {
this.setState({
description: editorState
})
}
render() {
const { release } = this.props.state;
return (
<div>
...
<CreateForm
description={this.state.description}
handleEditorState={this.handleEditorState}
handleSubmit={(e) => handleSubmit(e)}
/>
...
);
}
}
Form file
import { Editor } from 'react-draft-wysiwyg';
import '../../react-draft-wysiwyg.css';
class CreateForm extends Component {
render() {
const { description, handleEditorState, handleSubmit } = this.props;
return (
<div>
<form className="form-horizontal" onSubmit={handleSubmit}>
<Editor
editorState={description}
onEditorStateChange={handleEditorState}
/>
{/* Buttons */}
<div className={`modal-footer ${styles.modalFooter}`}>
...
</div>
</form>
</div>
);
}
}
Edit file
class EditAccessInstructionModal extends Component {
constructor(props) {
super(props);
this.state = {
description: EditorState.createEmpty()
}
}
componentWillMount(){
this.setState({
description: this.props.accessInstructions.description
});
}
componentWillReceiveProps(nextProps) {
this.setState({
description: nextProps.accessInstructions.description
});
}
onDescriptionChange(event) { this.setState({ description: event.target.value }); }
render() {
const { description } = this.state;
return (
<div className="btn-group">
<div className={`modal-body ${styles['proj-modal-body']}`}>
<form id="modalForm" className="form-horizontal">
<Editor
value={description}
/>
</form>
</div>
</div>
)
}
}