How to loop and render different components from array in ReactJs? - javascript

What implementation is needed to render different components from render method. As you can see below the idea is that Survey component receives an array which contains different components names (could be Input, CheckList, Dropdown, File). The array passes as property to Survey Component is generated properly depending of what button is clicked, but at the time to render different components is not working. I'm using JsComplete to test it.
const Dropdown = () =>{
return(
<div>
<select>
<option value="initial" selected>Select...</option>
<option value="Option ">Option 1</option>
<option value="Option ">Option 2</option>
</select>
</div>
)
}
const Checklist = () =>{
return(
<div>
<h4>Question name</h4>
<label>
Option 1:
<input
name="pl"
type="checkbox" />
</label>
<label>
Option 2:
<input
name="tz"
type="checkbox" />
</label>
</div>
)
}
const Input = () =>{
return(
<div>
<label>
Question name:
<input
name="input"
type="text" />
</label>
</div>
)
}
const File = () =>{
return(
<div>
<label>
Upload:
<input
name="file"
type="file" />
</label>
</div>
)
}
class Survey extends React.Component {
constructor(props){
super(props);
}
render(){
var ChildName ;
for (var i = 0; i < this.props.components.length; i++) {
log("Log:" + this.props.components[i]);
ChildName = this.props.components[i];
return <ChildName />;
}
return (
false
)
}
}
class Form extends React.Component {
handleSubmit = (name) => {
this.props.onSubmit(name);
};
render() {
return (
<div id="components">
<button onClick={()=>this.handleSubmit("Input")} name="Input">Input</button>
<button onClick={()=>this.handleSubmit("Checklist")} name="Checklist">Checkbox</button>
<button onClick={()=>this.handleSubmit("Dropdown")} name="Dropdown">Dropdown</button>
<button onClick={()=>this.handleSubmit("File")} name="File">File</button>
<div id="new-question">
</div>
</div>
)
}
}
class App extends React.Component {
state = {
components: []
};
addNewElement = (element) => {
this.setState(prevState => ({
components: prevState.components.concat(element)
}));
};
render() {
return (
<div>
<Form onSubmit={this.addNewElement} />
<Survey components={this.state.components} />
</div>
);
}
}
ReactDOM.render(<App />, mountNode);

Try this. Dont pass string in handleSubmit method. Instead pass component itself like this:
class Form extends React.Component {
handleSubmit = (name) => {
this.props.onSubmit(name);
};
render() {
return (
<div id="components">
<button onClick={()=>this.handleSubmit(Input)} name="Input">Input</button>
<button onClick={()=>this.handleSubmit(Checklist)} name="Checklist">Checkbox</button>
<button onClick={()=>this.handleSubmit(Dropdown)} name="Dropdown">Dropdown</button>
<button onClick={()=>this.handleSubmit(File)} name="File">File</button>
<div id="new-question">
</div>
</div>
)
}
}
Also in you survey component return the elements like this
class Survey extends React.Component {
constructor(props) {
super(props);
}
render() {
if (this.props.components.length === 0) {
return null;
}
const renderCommpos = this.props.components.map((Elem, index) => {
return <Elem key={index} />
});
return (
<div>
{renderCommpos}
</div>
);
}
}
Also notice the Elem in map function. When it comes to react component jsx needs the first letter capital. So doesn't matter what variable you keep at place of Elem, you should always keep the first letter capital.

The render method for your survey component should be like this :
render(){
const { components } = this.props;
return (
<div>
{
components.map((c, index) => {
return (
<div key={`one-of-components-${index}`}>
{c}
</div>
);
})
}
</div>
);
}
Now it will return all the components in the props.

Try this out.
const Survey = ({ components }) => {
const Components = components.map(
( component, index ) => {
return (
<div key={ index }>
{ component }
</div>
);
}
);
return (
<div>
{ Components }
</div>
);
};
In your for loop you're returning from the function on the first component. Add them to an array and then return the array. On another note, I used a functional stateless component here. I don't see the need for the class overhead.

Related

React: 2 way binding props

How can I do a 2 way binding of a variable from the parent component (Form.js), such that changes occurred in the child component (InputText.js) will be updated in the parent component?
Expected result: typing values in the input in InputText.js will update the state of Form.js
In Form.js
render() {
return (
<div>
<InputText
title="Email"
data={this.state.formInputs.email}
/>
<div>
Value: {this.state.formInputs.email} // <-- this no change
</div>
</div>
)
}
In InputText.js
export default class InputText extends React.Component {
constructor(props) {
super(props);
this.state = props;
this.handleKeyChange = this.keyUpHandler.bind(this);
}
keyUpHandler(e) {
this.setState({
data: e.target.value
});
}
render() {
return (
<div>
<label className="label">{this.state.title}</label>
<input type="text" value={this.state.data} onChange={this.handleKeyChange} /> // <-- type something here
value: ({this.state.data}) // <-- this changed
</div>
)
}
}
You can manage state in the parent component itself instead of managing that on child like this (lifting state up):
In Form.js
constructor(props) {
super(props);
this.handleKeyChange = this.keyUpHandler.bind(this);
}
keyUpHandler(e) {
const { formInputs } = this.state;
formInputs.email = e.target.value
this.setState({
formInputs: formInputs
});
}
render() {
// destructuring
const { email } = this.state.formInputs;
return (
<div>
<InputText
title="Email"
data={email}
changed={this.handleKeyChange}
/>
<div>
Value: {email}
</div>
</div>
)
}
In InputText.js
export default class InputText extends React.Component {
render() {
// destructuring
const { title, data, changed } = this.props;
return (
<div>
<label className="label">{title}</label>
<input type="text" value={data} onChange={changed} />
value: ({data})
</div>
)
}
}
You can also make your InputText.js a functional component instead of class based component as it is stateless now.
Update: (How to reuse the handler method)
You can add another argument to the function which would return the attribute name like this:
keyUpHandler(e, attribute) {
const { formInputs } = this.state;
formInputs[attribute] = e.target.value
this.setState({
formInputs: formInputs
});
}
And from your from you can send it like this:
<input type="text" value={data} onChange={ (event) => changed(event, 'email') } />
This assumes that you have different inputs for each form input or else you can pass that attribute name also from parent in props to the child and use it accordingly.
You would need to lift state up to the parent
parent class would look something like
onChangeHandler(e) {
this.setState({
inputValue: e.target.value // you receive the value from the child to the parent here
})
}
render() {
return (
<div>
<InputText
title="Email"
onChange={this.onChangeHandler}
value={this.state.inputValue}
/>
<div>
Value: {this.state.inputValue}
</div>
</div>
)
}
children class would look something like
export default class InputText extends React.Component {
constructor(props) {
super(props);
this.state = props;
}
render() {
return (
<div>
<label className="label">{this.state.title}</label>
<input type="text" value={this.state.value} onChange={this.props.onChange} />
value: ({this.state.value})
</div>
)
}
}
You can simply pass a callback from Form.js to InputText and then call that callback in InputText on handleKeyChange

React: Trigger button click from array map by another child

I have a parent component App and it has a child Content & Trigger. From the Content component, I have an array of content with radio button and a hidden button. The Trigger component has only one button. 🤔
My question is, how can I trigger a button click inside the Content component from the Trigger component depending on what the user selected on the Content component. 🤯
If my explanation is hard to understand, maybe my code does. Thank you. 🙏
CodeSandbox Sample
https://codesandbox.io/s/laughing-kirch-g2r10?fontsize=14&hidenavigation=1&theme=dark
App.js
import React from "react";
import Content from "./Content";
import Trigger from "./Trigger";
import "./styles.css";
class App extends React.PureComponent {
state = {
selectedOption: ""
};
onRadioButtonChange = name => {
this.setState({
selectedOption: name
});
};
onClickTriggerButton = e => {
const { selectedOption } = this.state;
e.preventDefault();
switch (selectedOption) {
case "opt1":
console.log("trigger click on option 1");
break;
case "opt2":
console.log("trigger click on option 2");
break;
case "opt3":
console.log("trigger click on option 3");
break;
default:
console.log("Select a method...");
}
};
render() {
return (
<div className="App">
<Content onRadioButtonChange={this.onRadioButtonChange} />
<Trigger onClickTriggerButton={this.onClickTriggerButton} />
</div>
);
}
}
export default App;
Content.js
import React from "react";
class Content extends React.PureComponent {
render() {
const { onRadioButtonChange } = this.props;
const tabs = [
{
name: "option_1_name",
content: (
<div className="Option-Method">
<input
type="radio"
name="group"
onChange={() => onRadioButtonChange("opt1")}
/>
Option Medthod 1 - Randon text...
<button
hidden
onClick={() => console.log("option 1 button clicked!")}
/>
</div>
)
},
{
name: "option_2_name",
content: (
<div className="Option-Method">
<input
type="radio"
name="group"
onChange={() => onRadioButtonChange("opt2")}
/>
Option Medthod 2 - Randon text...
<button
hidden
onClick={() => console.log("option 2 button clicked!")}
/>
</div>
)
},
{
name: "option_3_name",
content: (
<div className="Option-Method">
<input
type="radio"
name="group"
onChange={() => onRadioButtonChange("opt3")}
/>
Option Medthod 3 - Randon text...
<button
hidden
onClick={() => console.log("option 3 button clicked!")}
/>
</div>
)
}
];
return (
<form className="Content">
<fieldset id="group">
{tabs.map((attribute, index) => {
const key = `${attribute.name}-${index}`;
return (
<div key={key} className="Option">
{attribute.content}
</div>
);
})}
</fieldset>
</form>
);
}
}
export default Content;
Trigger.js
import React from "react";
class Trigger extends React.PureComponent {
render() {
const { onClickTriggerButton } = this.props;
return (
<div className="Trigger">
<button onClick={onClickTriggerButton}>Trigger Selected Option</button>
</div>
);
}
}
export default Trigger;
Pass ref to the Content component and for each hidden button check for the selectedOption if that matches set ref for that hidden button. Also wrap the Content component in React.forwardRef.
<button
hidden
ref={"opt1" === selectedOption ? ref : null}
onClick={() => console.log("option 1 button clicked!")}
/>
https://codesandbox.io/s/strange-hodgkin-jm84w?file=/src/Content.js:507-671

How to render an object with keys?

This is example code from a user named FrankerZ:
class ExampleComponent extends React.Component {
onBlur = async () => {
const results = await axios.get('myhttpendpoint');
this.setState({
results
});
}
render() {
return (
<div>
<form>
<span className="name"> Search Term: </span>
<input id="search-term" value={this.state.value} onBlur={this.onBlur} />
</form>
<div id="results">
{this.state.results}
</div>
</div>)
}
}
But essentially, my question is what if my axios.get returned an object with keys like
[{name: test1, data: datadatadata}, {name: test2, data: datatatatatata}]
How would I render each object in it's own span or own div?
I tried using a map such as
this.setState(results.map((item, index) => (<li key = {index}>{item.name}</li>)));
but it doesn't seem to work. I did this because it seems that React can't render object with keys and it told me to use an array instead which is what I tried.
You should do the map in the render method or any other method and call it in render, but not in set state.
Something like this
class ExampleComponent extends React.Component {
onBlur = async () => {
const results = await axios.get('myhttpendpoint');
this.setState({
results
});
}
render() {
return (
<div>
<form>
<span className="name"> Search Term: </span>
<input id="search-term" value={this.state.value} onBlur={this.onBlur} />
</form>
<div id="results">
{this.state.results.map(item => (<li key={item.name}>{item.name}</li>))}
</div>
</div>)
}
}
Markup should not go inside state.
Your render() should be like this.
<div id="results">
<ul>
{
this.state.results.map((item, index) => <li key = {index}>{item.name}</li>)
}
</ul>
</div>
make sure you initialize the state like this in constructor.
this.state = {
results : []
};
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
frank: [] // Basically, you will have a place in the state where you will save your data, which is empty.
}
componentDidMount(){
// This lifecycle method is used to fire requests.
// Fire your request.
// get the response.
// save the data only in the state, don't save ELEMENTS such like li.
const _result = [
{ id: 1, name: 'Frank1' },
{ id: 2, name: 'Frank2' }
];
this.setState({
frank: _result
});
}
render() {
const { frank } = this.state;
return (
<div>
<form>
<span className="name"> Search Term: </span>
<input id="search-term" value={this.state.value} onBlur={this.onBlur} />
</form>
<div id="results">
{/*HERE DO MAPPING*/}
{
frank.map((item, index) => <li key={index}>{item.name}</li>)
}
</div>
</div>)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Follow the comments up there.
live demo: https://codesandbox.io/s/kxv6myl8wo

how to add new input field after click plus icon in React Js

I'd like to add a new input everytime the plus icon is clicked but instead it always adds it to the end. I want it to be added next to the item that was clicked.
Here is the React code that I've used.
const Input = props => (
<div className="answer-choice">
<input type="text" className="form-control" name={props.index} />
<div className="answer-choice-action">
<i onClick={props.addInput}>add</i>
<i>Remove</i>
</div>
</div>
);
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
choices: [Input]
};
}
addInput = index => {
this.setState(prevState => ({
choices: update(prevState.choices, { $splice: [[index, 0, Input]] })
}));
};
render() {
return (
<div>
{this.state.choices.map((Element, index) => {
return (
<Element
key={index}
addInput={() => {
this.addInput(index);
}}
index={index}
/>
);
})}
</div>
);
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"));
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
I must admit this get me stuck for a while but there was a problem with how react deals with key props. When you use an index as a key it doesn't work. But if you make sure inputs will always be assigned the same key even when the list changes it will work as expected:
const Input = props => (
<div className="answer-choice">
<input type="text" className="form-control" name={props.index} />
<div className="answer-choice-action">
<i onClick={props.addInput}>add </i>
<i>Remove</i>
</div>
</div>
);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
choices: [],
nrOfElements: 0
};
}
addInput = index => {
this.setState(prevState => {
const choicesCopy = [...prevState.choices];
choicesCopy.splice(index, 0, `input_${prevState.nrOfElements}`);
return {
choices: choicesCopy,
nrOfElements: prevState.nrOfElements + 1
};
});
};
componentDidMount() {
this.addInput(0);
}
render() {
return (
<div>
{this.state.choices.map((name, index) => {
return (
<Input
key={name}
addInput={() => {
this.addInput(index);
}}
index={index}
/>
);
})}
</div>
);
}
}
Some reference from the docs:
Keys should be given to the elements inside the array to give the
elements a stable identity...
...We don’t recommend using indexes for keys if the order of items may
change. This can negatively impact performance and may cause issues
with component state.

React.js targeting a single element with a shared onClick function

I am new to both coding as well as React.js, so any assistance in learning what I am doing incorrectly is greatly appreciated! I am creating multiple cards on a page with riddles where the answer is hidden via css. I am using an onClick function ("toggleAnswer") to toggle the state of each answer to change the className so that the answer will either be visible or hidden. Currently, the onClick event is changing the state for all the answers. I realize this is because my code is not targeting a particular element, but I am unsure how this can be done. How can this be achieved? My code is currently like this:
// RiddlesPage where toggleAnswer function is defined
class RiddlesPage extends Component {
constructor(props) {
super(props);
this.state = {
questionData: [],
isHidden: true
};
this.getPageData = this.getPageData.bind(this);
this.toggleAnswer = this.toggleAnswer.bind(this);
}
getPageData() {
console.log("we hit getPageData function starting --");
helpers.getRiddlesPage().then(data => {
console.log("this is the result", data);
this.setState({
questionData: data[0].questionData,
});
});
}
toggleAnswer(e) {
this.setState({ isHidden: !this.state.isHidden });
}
componentWillMount() {
this.getPageData();
}
render() {
const answerClass = this.state.isHidden ? "answer-hide" : "answer";
return (
<div>
<Riddles>
{this.state.questionData.map((data, index) => {
return (
<RiddlesItem
key={index}
id={index}
question={data.question}
answer={data.answer}
button={data.buttonURL}
answerClass={answerClass}
onClick={this.toggleAnswer}
/>
);
})}
</Riddles>
</div>
);
}
}
export default RiddlesPage;
// Riddles Component
import React from "react";
import "./riddles.css";
const Riddles = props => (
<div id="riddles-row">
<div className="container">
<div className="row">
<div className="col-12">
<div>{props.children}</div>
</div>
</div>
</div>
</div>
);
export default Riddles;
// RiddlesItem Component where onClick function is set as a prop
import React from "react";
import "./riddles.css";
const RiddlesItem = props => (
<div>
<div className="card-body">
<p id="question">{props.question}</p>
<img
className="img-fluid"
id={props.id}
src={props.button}
onClick={props.onClick}
alt="answer button"
/>
<p className={props.answerClass}> {props.answer} </p>
</div>
</div>
);
export default RiddlesItem;
You'd have to keep track of each answer that has been shown in state (in an array or something).
First
Send the index of the answer up in the onclick function. In that function, check if it exists in the "shownAnswers" array and either add or remove it.
onClick={e => props.onClick(e, props.id)}
and
toggleAnswer(e, index) {
if (this.state.shownAnswers.indexOf(index) > -1) {
this.setState({
shownAnswers: this.state.shownAnswers.filter(val => val !== index)
});
} else {
this.setState({
shownAnswers: this.state.shownAnswers.concat(index)
});
}
}
Then
When you're passing the class name down to the child component, check if its index is in the "shownAnswers" array to decide which class name to pass.
answerClass={this.state.shownAnswers.indexOf(index) > -1 ? "answer" : "answer-hide"}
Building off your example, it could look something like this (untested):
// RiddlesPage where toggleAnswer function is defined
class RiddlesPage extends Component {
constructor(props) {
super(props);
this.state = {
questionData: [],
shownAnswers: []
};
this.getPageData = this.getPageData.bind(this);
this.toggleAnswer = this.toggleAnswer.bind(this);
}
getPageData() {
console.log("we hit getPageData function starting --");
helpers.getRiddlesPage().then(data => {
console.log("this is the result", data);
this.setState({
questionData: data[0].questionData,
});
});
}
toggleAnswer(e, index) {
if (this.state.shownAnswers.indexOf(index) > -1) {
this.setState({ shownAnswers: this.state.shownAnswers.filter(val => val !== index) });
} else {
this.setState({ shownAnswers: this.state.shownAnswers.concat(index) });
}
}
componentWillMount() {
this.getPageData();
}
render() {
return (
<div>
<Riddles>
{this.state.questionData.map((data, index) => {
return (
<RiddlesItem
key={index}
id={index}
question={data.question}
answer={data.answer}
button={data.buttonURL}
answerClass={this.state.shownAnswers.indexOf(index) > -1 ? "answer" : "answer-hide"}
onClick={this.toggleAnswer}
/>
);
})}
</Riddles>
</div>
);
}
}
export default RiddlesPage;
// Riddles Component
import React from "react";
import "./riddles.css";
const Riddles = props => (
<div id="riddles-row">
<div className="container">
<div className="row">
<div className="col-12">
<div>{props.children}</div>
</div>
</div>
</div>
</div>
);
export default Riddles;
// RiddlesItem Component where onClick function is set as a prop
import React from "react";
import "./riddles.css";
const RiddlesItem = props => (
<div>
<div className="card-body">
<p id="question">{props.question}</p>
<img
className="img-fluid"
id={props.id}
src={props.button}
onClick={e => props.onClick(e, props.id)}
alt="answer button"
/>
<p className={props.answerClass}> {props.answer} </p>
</div>
</div>
);
export default RiddlesItem;

Categories