I want to return the cloneElement of React

Asked 2 years ago, Updated 2 years ago, 146 views

I made the following components in React.
The data is for receiving the API

const Loop=({data,children})=>{
   return(
     <ul>{
      data.map(item,index)=>{
        return(
          React.cloneElement(
            children, {
             item
        })) 
      })
    }</ul>
  );
};

However, at this rate, I can only pass the components of the li element to children, so I would like to make them generic.
Due to the nature of React, I have to return some kind of DOM, so if I choose div, the li tag will not work this time, and the application will not work

Is it possible to create logic-only components without returning DOM in React?

javascript reactjs react-jsx redux

2022-09-29 22:02

1 Answers

How about handing over the parent components as well?
The Loop component implemented in the snippet below passes the repeating child element component and the wrapper that wraps it.

For example, <Loop data={data}component="li" wrapper="ul"/> will cause the original movement, and <Loop data={data}component="p" wrapper="div"/> if you want to use another element.

You can also pass components, so you can use <Loop data={data}component={Hello}wrapper="div"/>.

Or, like the repeatComponent function below, I think it's okay to take out only the part that makes the Loop component array.
JSX deploys when you put an array of components in a component, such as {componentArray}, so {repeatComponent(data, "li")} allows you to use only child elements.

var Hello=React.createClass({
  render: function() {
    return<div>Hello {this.props.name}</div>;
  }
});

const Loop=({data, component, wrapper})=>{
  const ItemComponent=component
  const Wrapper=wrapper
  return<Wrapper>
    { data.map(item,index)=>ItemComponent {...item}/>}
  </Wrapper>
}

const data=[{name:"world"}, {name:"again"}]

const repeatComponent=(data,ItemComponent)=>{
  return data.map(item,index)=>ItemComponent{...item}/>)
}

ReactDOM.render(
  <div>
  	<Loop data={data}component={Hello}wrapper={"div"}/>
    {repeatComponent(data,Hello)}
  </div>,
  document.getElementById('container')
);
<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>
<divid="container">
</div>


2022-09-29 22:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.